带有自定义 AuthenticationProvider 的 spring security 给出了拒绝访问错误

Posted

技术标签:

【中文标题】带有自定义 AuthenticationProvider 的 spring security 给出了拒绝访问错误【英文标题】:spring security with custom AuthenticationProvider gives access denied error 【发布时间】:2018-04-19 16:32:20 【问题描述】:

我正在尝试通过实现AuthenticationProvider 在我的应用程序中使用 Spring 安全性来实现自定义身份验证。身份验证成功,用户也具有指定的角色,但我仍然总是得到拒绝访问页面。下面是我的代码。我是春季安全的新手。请帮忙。提前致谢

Spring-security.xml

<form-login 
        login-page="/login"  login-processing-url="/j_spring_security_check"  default-target-url="/welcome" authentication-failure-url="/login?error" 
         />
         <access-denied-handler error-page="/403" />
    <logout logout-success-url="/login?logout"  /> 
     <csrf disabled="true"/>
</http>


<authentication-manager id="dao-auth" erase-credentials="false">
    <authentication-provider ref="customAuthenticationProvider">
    </authentication-provider>
</authentication-manager>

<b:bean id="customAuthenticationProvider" class="com.xom.custom.dataservice.impl.CustomAuthenticationProvider"></b:bean> 

CustomAuthenticationProvider

@Override
public Authentication authenticate(Authentication authentication) throws 
    AuthenticationException 

    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    final User rasUser;
    try 
        rasUser = checkPrivileges(name, password);
     catch (NoRASUserLoginException exception) 
        throw new ServiceException(0, "exception while retrieving user data  " + exception);
     catch (SQLException exception) 
        throw new ServiceException(0, "exception while retrieving user privilages " + name + exception);
    

    // userValue = (UserDetails) rasUser;
    if (rasUser == null)
        throw new UsernameNotFoundException(name + " not found");

       List<SimpleGrantedAuthority> auths = new 
      java.util.ArrayList<SimpleGrantedAuthority>();
      for (String privilege : rasUser.getPermissions()) 
        if (privilege != null && privilege.equalsIgnoreCase("RReportAdmin")) 
      
            auths.add(new 
          SimpleGrantedAuthority("ROLES_".concat(privilege)));
        
    
    auths = auths.stream().distinct().collect(Collectors.toList());
    authentication = new UsernamePasswordAuthenticationToken(name, password, auths);
    return authentication;

登录.jsp

<html>
    <head>
       <title>Login</title>
    </head>
    <body onload='document.loginForm.username.focus();'>
        <h1>Spring Security Custom Login Form (XML)</h1>
         <div id="login-box">
         <h3>Login with Username and Password</h3>

         <form name='loginForm'
         action="<c:url value='/j_spring_security_check' />" method='POST'>

         <table>
            <tr>
                <td>User:</td>
                <td><input type='text' name='username'></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type='password' name='password' /></td>
            </tr>
            <tr>
                <td colspan='2'><input name="submit" type="submit"
                    value="submit" /></td>
            </tr>
        </table>
       </form>
      </div>
     </body>
</html>

日志

2017-11-07 03:47:42,212 DEBUG o.s.s.w.u.m.AntPathRequestMatcher [http-nio-8080-exec-15] 检查请求匹配:'/admin';反对“/管理员” 2017-11-07 03:47:42,214 调试 o.s.s.a.i.AbstractSecurityInterceptor [http-nio-8080-exec-15] 安全对象:FilterInvocation:URL:/admin;属性:[hasRole('ROLES_RReportAdmin')] 2017-11-07 03:47:42,214 调试 o.s.s.a.i.AbstractSecurityInterceptor [http-nio-8080-exec-15] 先前已验证:org.springframework.security.authentication.UsernamePasswordAuthenticationToken@e68aaf8b: 校长:rparwee;凭证:[受保护];已认证:真实; 细节: org.springframework.security.web.authentication.WebAuthenticationDetails@1c07a: 远程IP地址:127.0.0.1;会话 ID: EE3501D56ED257409E40A4F8D5F6F794;授予权限: ROLES_RReportAdmin 2017-11-07 03:47:42,216 调试 o.s.s.a.v.AffirmativeBased [http-nio-8080-exec-15] 选民: org.springframework.security.web.access.expression.WebExpressionVoter@6102b9a6, 返回:-1 2017-11-07 03:47:42,219 TRACE o.s.c.s.AbstractApplicationContext [http-nio-8080-exec-15] 在 WebApplicationContext 中发布事件 命名空间'mvc-dispatcher-servlet': org.springframework.security.access.event.AuthorizationFailureEvent[source=FilterInvocation: 网址:/管理员] 2017-11-07 03:47:42,219 调试 o.s.s.w.a.ExceptionTranslationFilter [http-nio-8080-exec-15] 访问是 拒绝(用户不是匿名的);委托给 AccessDeniedHandler org.springframework.security.access.AccessDeniedException:访问被拒绝 在 org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] 在 org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] 在 org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] 在 org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]

【问题讨论】:

【参考方案1】:

我弄错了。在检查授权之前检查“ROLE”。在我的情况下,我添加了“角色”。

代码从 intercept-url pattern="/admin**" access="hasRole('ROLES_RReportAdmin')" 更改为 intercept-url pattern="/admin**" access="hasRole ('ROLE_RReportAdmin')"

【讨论】:

【参考方案2】:

请尝试添加

access="permitAll" in Spring-security.xml for login-page="/login"

也可以在 /welcome 中访问="hasRole('ROLE_RReportAdmin')"

【讨论】:

感谢您的回复。但添加后它也无法正常工作。我尝试对用户名和密码进行硬编码,然后它就可以工作了。但是从数据库中获取详细信息时它不起作用。 成功日志 o.s.s.w.u.m.AntPathRequestMatcher [http-nio-8080-exec-25] 检查请求匹配:'/admin';针对 '/admin**' o.s.s.a.i.AbstractSecurityInterceptor [http-nio-8080-exec-25] 安全对象:FilterInvocation:URL:/admin;属性:[hasRole('ROLE_USER')] ossaiAbstractSecurityInterceptor [http-nio-8080-exec-25] 先前认证:org.springframework.security.authentication.UsernamePasswordAuthenticationToken@840354ab:主体:org.springframework.security.core.userdetails.User@ c01cbded:用户名:mkyong;密码保护];启用:真; AccountNonExpired:真;凭据非过期:真; AccountNonLocked:真;授予权限:ROLE_USER;凭证:[受保护];已认证:真实;详细信息:org.springframework.security.web.authentication.WebAuthenticationDetails@2eb76: ;授予权限:ROLE_USER ossavAffirmativeBased [http-nio-8080-exec-25] 投票者:org.springframework.security.web.access.expression.WebExpressionVoter@44f6daea,返回:1 ossaiAbstractSecurityInterceptor [http-nio-8080 -exec-25] 授权成功 失败日志 o.s.s.w.u.m.AntPathRequestMatcher [http-nio-8080-exec-7] 检查请求匹配:'/admin';针对 '/admin**' o.s.s.a.i.AbstractSecurityInterceptor [http-nio-8080-exec-7] 安全对象:FilterInvocation:URL:/admin;属性:[hasRole('ROLES_RReportAdmin')]

以上是关于带有自定义 AuthenticationProvider 的 spring security 给出了拒绝访问错误的主要内容,如果未能解决你的问题,请参考以下文章

带有自定义按钮的自定义 UIAlertView

带有自定义数据的自定义 UIActivity

自定义 Combobox 控件自定义数据源,带有自定义 displaymember 和 valuemember

带有自定义后退导航按钮的自定义按钮栏

带有 xib 文件和自定义构造函数的自定义 UITableViewCell

带有自定义 slug 的 wordpress 自定义帖子类型并获取变量