【问题标题】:Spring Security two roles implementationSpring Security 两个角色的实现
【发布时间】:2018-07-28 23:17:08
【问题描述】:

我是弹簧安全方法的新手。我正在尝试在我的 Web 应用程序中实现两个用户。 (管理员角色和用户角色) 我有两个重定向页面使用 thymeleaf 进行管理,它应该下降到 /admin/** 并且对于用户它应该是 /user/**

我尝试使用@order(1) 和 order(2) 添加两个 spring 安全类,但仍然无法正常工作。我的目标是,如果用户登录并且在我的安全中具有角色,它应该重定向到正确的页面。

请看下面我的代码

spring.queries.users-query=select email, password, enabled from user where email=?
spring.queries.roles-query=select u.email, r.role from user u inner join user_role ur on (u.id=ur.user_id) inner join role r on(ur.role_id=r.role_id) where u.email=?

    @Override
protected void configure(AuthenticationManagerBuilder auth)
        throws Exception {
    auth.
        jdbcAuthentication()
            .usersByUsernameQuery(usersQuery)
            .authoritiesByUsernameQuery(rolesQuery)
            .dataSource(dataSource)
            .passwordEncoder(bCryptPasswordEncoder);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers("/login").permitAll()
        .antMatchers("/register").permitAll()
        .antMatchers("/confirm").permitAll()
        .antMatchers("/forgotpassword").permitAll()
        .antMatchers("/criminal/getAllWantedCriminal").permitAll()
        .antMatchers("/criminal/viewCriminal").permitAll()
        .antMatchers("/admin/**").hasAuthority("ADMIN")
        .antMatchers("/user/**").hasAuthority("USER")
        .anyRequest()
        .authenticated().and().csrf().disable().formLogin()
        .loginPage("/login").failureUrl("/login?error=true")
        .defaultSuccessUrl("/admin/home")
        .usernameParameter("email")
        .passwordParameter("password")
        .and().logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl("/").and().exceptionHandling()
        .accessDeniedPage("/access-denied");
}

【问题讨论】:

  • 你也可以发布你的控制器吗?

标签: java spring spring-boot spring-security


【解决方案1】:

实现这一点的最简单方法是创建自定义org.springframework.security.web.authentication.AuthenticationSuccessHandler

在那里,一旦用户正确登录,您就可以检查 Authentication 对象有 ROLE_ADMIN 重定向到默认配置的成功 url(默认用户成功 url)或管理员。这是一个工作示例,扩展 org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler:

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

public class RoleBasedAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler
        implements AuthenticationSuccessHandler {

    private String adminRoleTargetUrl;

    private String adminRoleAuthority;

    /**
     * @param defaultTargetUrl
     */
    public RoleBasedAuthenticationSuccessHandler(String defaultTargetUrl, String adminRoleTargetUrl, String adminRoleAuthority) {
        super(defaultTargetUrl);
        this.adminRoleTargetUrl = adminRoleTargetUrl;
        this.adminRoleAuthority = adminRoleAuthority;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        if(isAdmin(authentication)){
            this.getRedirectStrategy().sendRedirect(request, response, this.getAdminRoleTargetUrl());
            return;
        }
        super.onAuthenticationSuccess(request, response, authentication);
    }

    /**
     * @param authentication
     */
    protected boolean isAdmin(Authentication authentication) {
        for(GrantedAuthority authority : authentication.getAuthorities()){
            if(authority.getAuthority().equals(this.getAdminRoleAuthority())){
                return true;
            }
        }
        return false;
    }

    /**
     * @return the adminRoleTargetUrl
     */
    public String getAdminRoleTargetUrl() {
        return adminRoleTargetUrl;
    }

    /**
     * @return the adminRoleAuthority
     */
    public String getAdminRoleAuthority() {
        return adminRoleAuthority;
    }   

}

然后,更改您的安全配置类,以便在方法successHandler 中设置RoleBasedAuthenticationSuccessHandler 实例,而不是使用defaultSuccessUrl

@Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.
        jdbcAuthentication()
        .usersByUsernameQuery(usersQuery)
        .authoritiesByUsernameQuery(rolesQuery)
        .dataSource(dataSource)
        .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers("/login").permitAll()
        .antMatchers("/register").permitAll()
        .antMatchers("/confirm").permitAll()
        .antMatchers("/forgotpassword").permitAll()
        .antMatchers("/criminal/getAllWantedCriminal").permitAll()
        .antMatchers("/criminal/viewCriminal").permitAll()
        .antMatchers("/admin/**").hasAuthority("ADMIN")
        .antMatchers("/user/**").hasAuthority("USER")
        .anyRequest()
        .authenticated().and().csrf().disable().formLogin()
        .loginPage("/login").failureUrl("/login?error=true")
        .successHandler(this.getSuccessHandler())
        .usernameParameter("email")
        .passwordParameter("password")
        .and().logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl("/").and().exceptionHandling()
        .accessDeniedPage("/access-denied");
    }

    private AuthenticationSuccessHandler getSuccessHandler() {
        return new RoleBasedAuthenticationSuccessHandler(
                    "/user/home",
                    "/admin/home",
                    "ROLE_ADMIN"                
                );

    }

【讨论】:

  • 我会努力实现的。
猜你喜欢
  • 2014-05-01
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 2011-08-16
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 2019-12-19
相关资源
最近更新 更多