具有角色的经过身份验证的用户的Spring Security Java配置 [英] Spring Security Java configuration for authenticated users with a role

查看:167
本文介绍了具有角色的经过身份验证的用户的Spring Security Java配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有Spring Boot的Java配置来配置Spring Security。

I am trying to configure Spring Security using Java configuration with Spring Boot.

我的WebSecurityConfig类有这样的配置方法

My WebSecurityConfig class has a configure method like this

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/", "/login", "/css/**", "/js/**", "/img/**", "/bootstrap/**" ).permitAll()
            .antMatchers("/individual", "/application", "/upload").hasRole("USER")
        .and()
            .formLogin()
                .loginPage("/login")
                .successHandler(successHandler);

}

我为未经身份验证的用户提供了登录页面,并且用户进行身份验证但是,当试图访问网址/个人时,我收到403错误,这在日志中

I get the login page fine for unauthenticated users, and the user authenticates. However, when trying to access the url /individual I get a 403 error and this in the log

2015-11-12 13:59:46.373 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/individual'; against '/'
2015-11-12 13:59:46.373 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/individual'; against '/login'
2015-11-12 13:59:46.373 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/individual'; against '/css/**'
2015-11-12 13:59:46.373 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/individual'; against '/js/**'
2015-11-12 13:59:46.374 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/individual'; against '/img/**'
2015-11-12 13:59:46.374 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/individual'; against '/bootstrap/**'
2015-11-12 13:59:46.374 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/individual'; against '/individual'
2015-11-12 13:59:46.374 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /individual; Attributes: [hasRole('ROLE_USER')]
2015-11-12 13:59:46.374 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@4c2eda81: Principal: org.springframework.security.core.userdetails.User@4c0ab982: Username: foo@bar.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffc7f0c: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 6E0BF830C070912EAC0050D1285D5CF9; Granted Authorities: USER
2015-11-12 13:59:46.374 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@6f192fd7, returned: -1
2015-11-12 13:59:46.386 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is not anonymous); delegating to AccessDeniedHandler

如果我替换 .hasRole(USER) with .authenticated()它可以工作,用户获得所需的页面,但没有检查任何角色。

if I replace .hasRole("USER") with .authenticated() it works and the user gets the page desired, but no role is being checked.

我无法弄清楚如何指定用户必须经过身份验证并具有USER角色。我已经看了很多例子并尝试了很多组合,但我无法让它按照需要运行。大多数示例也引用了较旧的基于XML的配置,我想避免这种配置。

I cannot figure out how to specify that the user must be authenticated and have the role USER. I have looked at many examples and tried many combinations but I cannot get it to work as desired. Most of the examples refer to older XML based configuration as well, which I want to avoid.

我需要做些什么才能指定可以访问某些URL模式具有特定角色的经过身份验证的用户?

What do I need to do to specify that certain URL patterns can be accessed with authenticated users with certain roles?

根据要求,成功处理程序方法如下所示

As requested, the success handler method looks like this

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth)
        throws IOException, ServletException {

    // Here we want to check whether the user has already started the process and redirect to the appropriate stage

    log.info("User {} has been authenticated", auth.getName());

    if(auth.getName().equals("foo@bar.com"))
    {
        redirectStrategy.sendRedirect(request, response, "/individual");
        return;
    }


    redirectStrategy.sendRedirect(request, response, "/application");

}

请注意,这是早期的WIP,根据评论代码。我知道这有效,因为日志消息出现并且在WebSecurity类中没有角色检查所需的页面被提供。

Note that this is early stage WIP, per the comments in the code. I know this works as the log message appears and without the role check in the WebSecurity class the desired page is served.

编辑:注意到在提到roleService的问题中的拼写错误.getDefaultRole()。这是一个错误,并已得到纠正。

EDIT : noticed a typo in the question referring to roleService.getDefaultRole(). This was a mistake and has been corrected.

推荐答案

我认为您登录的用户foo@bar.com设置了错误的权限。在日志中,您可以看到权限是['USER'],但由于您正在使用角色,因此它应该是['ROLE_USER']。你在哪里定义foo@bar.com的权限?

I think your logged in user foo@bar.com has the wrong authorities set. In the log you can see the authorities are ['USER'], but since you are working with roles it should be ['ROLE_USER']. Where do you define the authorities for foo@bar.com?

否则尝试切换

.antMatchers("/individual", "/application", "/upload").hasRole("USER")

.antMatchers("/individual", "/application", "/upload").hasAuthority("USER")

这篇关于具有角色的经过身份验证的用户的Spring Security Java配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆