問題描述
使用 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("/show‑menu‑list‑admin").hasRole("ADMIN")
.antMatchers("/show‑menu‑list‑customer").hasRole("USER").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 Sahoo、Eleftheria Stein‑Kousathana)
參考文件