【问题标题】:Custom AuthenticationProvider for Spring Security 4.2.1Spring Security 4.2.1 的自定义 AuthenticationProvider
【发布时间】:2017-05-27 12:13:29
【问题描述】:

大家好,这篇文章是关于 Spring Security 和 AuthenticationProvider 的自定义实现 我正在为我的应用程序使用以下配置 JDK 1.8 春天 4.3.5 休眠 5.2.6 Spring Security 4.2.1

问题在于 AuthenticationProvider 的自定义实现,我可以登录,但指定角色的访问管理不起作用。

这是我的 Spring-security.xml 代码

<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/**" access="isAuthenticated()"/>
    <intercept-url pattern="/home.htm" access="permitAll" />
    <intercept-url pattern="/login.htm" access="permitAll" />
    <intercept-url pattern="/registerUser.htm" access="hasRole('ROLE_ADMIN')" />
    <intercept-url pattern="/manageUser.htm" access="hasRole('ROLE_ADMIN')" />
    <intercept-url pattern="/manageProject.htm" access="permitAll" />


    <!-- Manage user login logout -->
    <form-login login-processing-url="/j_spring_security_check" login-page="/login.htm" authentication-failure-handler-ref="customAuthenticationFailureHandler" authentication-success-handler-ref="customAuthenticationSuccessHandler"/>
    <logout logout-url="/logout.htm" delete-cookies="true" invalidate-session="true" />
    <csrf disabled="true"/>
</http>

<beans:bean id="customAuthenticationSuccessHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler">
    <beans:property name="defaultTargetUrl" value="/home.htm" />
</beans:bean>   

<beans:bean id="customAuthenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
    <beans:property name="defaultFailureUrl"  value="/login.htm?error=true"/>
</beans:bean>   
<beans:bean id="myAuthenticationProvider" class="com.rolta.scan.serviceImpl.CustomAuthenticationProviderImpl"/>

<authentication-manager alias="authenticationManager">
    <authentication-provider ref="myAuthenticationProvider" />
</authentication-manager>

CustomAuthenticationProviderImpl.java

private Logger LOGGER = Logger.getLogger(CustomAuthenticationProviderImpl.class);

@Autowired
private CustomUserRepository userService;

@Autowired
private UserLoginsRepository userLoginService;

@Autowired
private T_CustomUserBean user;

@Autowired
private T_UserLogins tUserLogins;

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
          SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH-mm-SS");   
          String username = authentication.getPrincipal().toString();
          String password = authentication.getCredentials().toString();
          //String message="Wrong Username or Password";
          Collection<? extends GrantedAuthority> authorities=null ;
          tUserLogins.setLoginId(authentication.getPrincipal().toString());
          ServletRequestAttributes attr =(ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
          HttpSession session = attr.getRequest().getSession(true);
          HttpServletRequest request = attr.getRequest();
          tUserLogins.setSessionId(attr.getRequest().getSession().getId());
          tUserLogins.setLoginIpAddress(attr.getRequest().getRemoteAddr());
          tUserLogins.setLoginPassword(password);
          tUserLogins.setLoginId(username);
          tUserLogins.setLoginDtTime(new Date().toString());
          tUserLogins.setLoginStatus("");
          tUserLogins.setEventName("");
          tUserLogins.setForwarded_for(request.getHeader("X-Forwarded-For"));  
          tUserLogins.setProxy_client_ip(request.getHeader("Proxy-Client-IP"));  
          tUserLogins.setWl_proxy_client_ip(request.getHeader("WL-Proxy-Client-IP"));  
          tUserLogins.setHttp_x_forwarded_for(request.getHeader("HTTP_X_FORWARDED_FOR"));  
          tUserLogins.setHttp_x_forwarded(request.getHeader("HTTP_X_FORWARDED"));  
          tUserLogins.setHttp_cluster_client_ip(request.getHeader("HTTP_X_CLUSTER_CLIENT_IP"));  
          tUserLogins.setHttp_client_ip(request.getHeader("HTTP_CLIENT_IP"));  
          tUserLogins.setHttp_forwarded_for(request.getHeader("HTTP_FORWARDED_FOR"));  
          tUserLogins.setHttp_forwarded(request.getHeader("HTTP_FORWARDED"));  
          tUserLogins.setHttp_via(request.getHeader("HTTP_VIA"));  
          tUserLogins.setRemote_addr(request.getHeader("REMOTE_ADDR"));  


          user= userService.loadUserByName(username);

      if (user.getUsername().equalsIgnoreCase(username) && password.equals(user.getPassword()) && user.isEnabled()){
      try{

            userLoginService.saveUserLogins(tUserLogins);
            LOGGER.info("User logged in successfully with user name :"+username);
            authorities= getGrantedAuthorities(user);

        }
          catch(Exception se){
              LOGGER.error("Exception occured Ddue to "+se.getMessage());
              LOGGER.error("Exception occured Ddue to "+se.getStackTrace());
          }
      }
      else {
          System.out.println("in else");
            throw new BadCredentialsException("");
        }
      return new UsernamePasswordAuthenticationToken(username, password, authorities);


private List<GrantedAuthority> getGrantedAuthorities(T_CustomUserBean user){
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for(T_CustomRole userProfile : user.getAuthorities()){
        authorities.add(new SimpleGrantedAuthority(userProfile.getAuthority()));
    }
    return authorities;
}

@Override
public boolean supports(Class<?> authentication) {
    return authentication.equals(UsernamePasswordAuthenticationToken.class);
}

我可以登录,所以身份验证工作正常,但 URL 授权工作不正常。某些 URL 只能由我们分配了 ROLE_ADMIN 的用户访问,但这不起作用,任何具有任何角色的用户都可以访问每个 URL。

【问题讨论】:

    标签: hibernate spring-mvc spring-security


    【解决方案1】:
    <intercept-url pattern="/home.htm" access="permitAll" />
    <intercept-url pattern="/login.htm" access="permitAll" />
    <intercept-url pattern="/registerUser.htm" access="hasRole('ROLE_ADMIN')" />
    <intercept-url pattern="/manageUser.htm" access="hasRole('ROLE_ADMIN')" />
    <intercept-url pattern="/manageProject.htm" access="permitAll" />
    <intercept-url pattern="/**" access="isAuthenticated()"/>
    

    请更改拦截网址顺序。更多详情见here

    【讨论】:

    • 这样做没有改变问题在于角色,URL /registerUser.htm/manageUser.htm 只能由以下用户访问有 ROLE_ADMIN 否则它应该通过 403 access denied 错误但我仍然可以访问这些 URL 的任何角色。
    猜你喜欢
    • 2012-01-28
    • 2014-10-06
    • 2016-12-07
    • 2017-01-09
    • 2015-10-16
    • 2019-11-06
    • 2021-03-19
    • 2018-02-06
    • 2011-01-20
    相关资源
    最近更新 更多