簡體   English   中英

Spring Security的兩個角色實現

[英]Spring Security two roles implementation

我是Spring安全方法的新手。 我正在嘗試在我的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");
}

實現此目的的最簡單方法是創建自定義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"                
                );

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM