具有角色的Spring安全性

时间:2015-08-02 20:34:26

标签: spring spring-security spring-boot

我知道,这个问题已多次发布,但所有答案都没有帮助我,我也会在这里发布我的案例。

我的SpringBoot-Project配置如下:

SecurityConfig

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/secure/**")
                .authorizeRequests()
                .anyRequest()
                .hasRole(ERole.USER.name);

        http.formLogin().loginPage("/auth").permitAll();
    }
}

带角色的枚举

public enum ERole implements GrantedAuthority {
    USER("USER");

    public final String name;

    ERole(String name) {
        this.name = name;
    }

    @Override
    public String getAuthority() {
        return this.name;
    }
}

自定义身份验证

public class UserAuth implements Authentication {
    // Implements all the methods ...
    // getAuthorities() return the list of ERole
}

Auth REST控制器

@RestController
public class AuthRestCtrl {
    public static final String PERMIT_URL = AuthCtrl.INDEX_URL + "/rest/permit";

    private ShaPasswordEncoder shaPasswordEncoder = new ShaPasswordEncoder();

    /**
     * Führt die Authentifizierung des Nutzers durch
     */
    @RequestMapping(value = "/auth/rest/permit", method = RequestMethod.POST)
    public boolean permitUser(@RequestBody AuthData authData) {
        Account account = new Account();
        account.setLogin("test");
        account.setSalt("");
        account.setPassword(this.shaPasswordEncoder.encodePassword("123456", account.getSalt()));
        account.addRole(ERole.USER);

        User user = new User();
        user.setName("...");
        user.setSurname("...");
        user.setAccount(account);

        if (!authData.getUsername().equals(account.getLogin())) {
            return false;
        }

        if (!this.shaPasswordEncoder.isPasswordValid(account.getPassword(), authData.getPassword(), account.getSalt())) {
            return false;
        }

        UserAuth userAuth = new UserAuth(user);
        userAuth.setAuthenticated(true);
        SecurityContextHolder.getContext().setAuthentication(userAuth);

        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        attr.getRequest().getSession(true).setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());
        return true;
    }

现在,如果我重定向(通过我的restclient返回true后的javascript)到任何安全页面“/ secure / home”我得到状态403.我读到状态403意味着用户有错误的角色,但不知道我做错了什么。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

好的,我发现了。在SecurityConfig on" .hasRole(ERole.USER.name);" spring会自动附加 ROLE _ 前缀。但是用户具有 USER 的角色,而不是 ROLE_USER 。我在 getAuthority() -method:

中解决了这个问题
@Override
public String getAuthority() {
    return "ROLE_" + this.name;
}

我知道我使用SpringSecurity eventuelly不正确的方式,但这对我来说很有效(在我的SpringBoot测试项目中)