使用 Spring Security 根據用戶角色登錄後重定向到不同的頁面 (Redirect to different page after login based on user role with Spring Security)


問題描述

使用 Spring Security 根據用戶角色登錄後重定向到不同的頁面 (Redirect to different page after login based on user role with Spring Security)

<div class="snippet" data‑lang="js" data‑hide="false" data‑console="true" data‑babel="false">

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO‑8859‑1">
<title>Welcome to Akash Home</title>
<link rel="stylesheet" type="text/css"
href="/webjars/bootstrap/css/bootstrap.min.css" />
<script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script>
<script type="text/javascript"
src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container text‑center">
<h1>Welcome to the portal</h1>
<h3>
<a href="/register">Register</a>
</h3>
<h3>
<a href="show‑menu‑list‑admin">Login as a admin</a><br>
<a href="show‑menu‑list‑customer">Login as a user</a><br>
<!‑‑ <a href="login">login</a> ‑‑>
<a href="logout">logout</a>
</h3>
</div>

</body>
</html></code></pre> </div> </div> </p>

在這裡,我創建了單獨的鏈接,用於以管理員/用戶身份登錄。如何根據輸入的憑據添加單個登錄頁面重定向到下一頁:如果 user1 是管理員,如果輸入了他的憑據,他將被重定向到管理頁面,反之亦然以進行用戶登錄

這是我的 spring 安全配置代碼:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Bean
public UserDetailsService getUserDetailService() {
    return new UserDetailsServiceImpl();
}

@Bean
public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

@Bean
public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
    daoAuthenticationProvider.setUserDetailsService(this.getUserDetailService());
    daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());

    return daoAuthenticationProvider;
}

// authentication ‑ configure method

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers(&quot;/show‑menu‑list‑admin&quot;).hasRole(&quot;ADMIN&quot;)
            .antMatchers(&quot;/show‑menu‑list‑customer&quot;).hasRole(&quot;USER&quot;).and().formLogin().and().csrf().disable();
}

}
</code></pre>


參考解法

方法 1:

You can supply a custom AuthenticationSuccessHandler.
The AuthenticationSuccessHandler is what tells Spring Security what to do after a successful user authentication.
The default implementation typically uses a SimpleUrlAuthenticationSuccessHandler, which redirects users to the supplied URL once they successfully authenticate.

In your custom implementation, you can delegate to a different SimpleUrlAuthenticationSuccessHandler based on the user's role.

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    SimpleUrlAuthenticationSuccessHandler userSuccessHandler =
            new SimpleUrlAuthenticationSuccessHandler("/user‑page");
    SimpleUrlAuthenticationSuccessHandler adminSuccessHandler =
            new SimpleUrlAuthenticationSuccessHandler("/admin‑page");

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (final GrantedAuthority grantedAuthority : authorities) {
            String authorityName = grantedAuthority.getAuthority();
            if (authorityName.equals("ROLE_ADMIN")) {
                // if the user is an ADMIN delegate to the adminSuccessHandler
                this.adminSuccessHandler.onAuthenticationSuccess(request, response, authentication);
                return;
            }
        }
        // if the user is not an admin delegate to the userSuccessHandler
        this.userSuccessHandler.onAuthenticationSuccess(request, response, authentication);
    }
}

Then, supply the CustomAuthenticationSuccessHandler in the form login configuration.

http
    .formLogin(formLogin ‑> formLogin
        .successHandler(new CustomAuthenticationSuccessHandler())
    );

(by Akash Kumar SahooEleftheria Stein‑Kousathana)

參考文件

  1. Redirect to different page after login based on user role with Spring Security (CC BY‑SA 2.5/3.0/4.0)

#java #spring-boot #hibernate #spring-security






相關問題

電子郵件地址中帶有 + 字符的 Java 郵件 (Java mail with + character in email address)

如何快速原型化 Java 代碼? (How to quickly prototype Java code?)

如何使用 Maven 在目標(SVN-)服務器上創建 Javadoc? (How to create Javadoc on the target (SVN-) server using Maven?)

為什麼檢查二叉樹有效性的解決方案不起作用? (Why the solution for checking the validity of binary tree is not working?)

Selenium webdriver通過第一個數字找到texy (Selenium webdriver find texy by first digits)

setOnClickListener 沒有在圖像視圖上被調用 (setOnClickListener is not getting called on image view)

繪製多邊形:找不到錯誤 (Drawing Polygon : unable to find error)

半透明 JButton:對像出現在背景中 (Semi-Transparent JButton: Objects appear in Background)

比較同一數組的元素 (Compare elements of the same array)

Java 屏幕截圖小程序 (Java screen capture applet)

Minecraft 1.8.9 Forge Modding 的Java 開發工具包,需要什麼JDK/JRE,代碼是否正確? (Java Development Kit with Minecraft 1.8.9 Forge Modding, What JDK/JRE Is Needed, Is Code Correct?)

java while (resultset.next()) 不返回同一列中的所有數據 (java while (resultset.next()) does not return all data in the same column)







留言討論