如何在春天使用基于表达式的访问控制?

时间:2017-07-28 04:02:37

标签: java spring spring-boot spring-security

我是spring的新手。我为用户登录创建了一个api。用户登录方法包含以下代码:

Authentication auth =new UsernamePasswordAuthenticationToken(repo.findByEmail(user.getEmail()), null, repo.findByEmail(user.getEmail()).getAuthorities());

SecurityContextHolder.getContext().setAuthentication(auth);
Principal principal= SecurityContextHolder.getContext().getAuthentication();
return (User) auth.getPrincipal();

登录api给了我以下json:

{
"userId": 1,
"userName": "ramesh khadka",
"email": "test@gmail.com",
"enabled": true,
"role": "Manager",
"username": "ramesh khadka",
"authorities": [
    {
        "authority": "ROLE_Manager"
    }
],
"accountNonExpired": true,
"accountNonLocked": true,
"credentialsNonExpired": true
}

我有另一个api让所有使用@PreAuthorize的用户(“hasAuthority('ROLE_Manager')”)检查授权的权限。当我调用api时,会显示以下消息: -

{
"error": "unauthorized",
"error_description": "Full authentication is required to access this resource"
}

我无法弄清楚我做错了什么。有人可以帮我吗?

我的授权服务器是: -

@Configuration
@EnableAuthorizationServer
public class SecurityServer extends AuthorizationServerConfigurerAdapter {
@Autowired
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;

@Autowired
private AuthenticationManager authenticationManager;

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    security.checkTokenAccess("isAuthenticated()");
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    // super.configure(clients);
    clients.inMemory()
            .withClient("test")
            .accessTokenValiditySeconds(3600)
            .authorizedGrantTypes("authorization_code","refresh_token","password","client_credentials")
            .secret("user")
            .scopes("read", "write", "trust")
            .redirectUris("/error")
            .resourceIds("resource");
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.authenticationManager(this.authenticationManager);
    endpoints.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
}

}

1 个答案:

答案 0 :(得分:0)

如您的代码所述,您使用'@PreAuthorize(“hasAuthority('ROLE_Manager')”)'

hasAuthority([权限]) - >如果当前主体具有指定的权限,则返回true。

请添加'@PreAuthorize(“hasRole('Manager')”)`

@PreAuthorize("hasRole('USER')")
public void create(Contact contact);

要么你可以使用这个作为你的任何角色 正在寻找然后检查  hasAnyRole([role1,role2]) - >如果当前主体具有任何提供的角色(以逗号分隔的字符串列表给出),则返回true。默认情况下,如果提供的角色不以“ROLE_”开头,则会添加该角色。这可以通过修改DefaultWebSecurityExpressionHandler上的defaultRolePrefix来自定义。

有关更多信息,请参阅以下链接: https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html https://dzone.com/refcardz/expression-based-authorization