如何使用Spring Security自定义登录页面?
我正在对应用程序使用Spring Security,这是用于验证用户身份的安全性部分,但登录页面由Spring Security提供:
@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
.antMatchers("/home*").hasRole("USER")
.and()
.formLogin();
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER")
}
}
我想使用下面的我的登录页面来代替Spring的登录页面:
login.html
:
<html lang='en'> <head>
<title>WebApp</title>
<meta charset='utf-8' />
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<link rel="stylesheet" href="css/login.css" />
</head>
<body>
<div class="login-page">
<img src='img/taxi_.jpg' style='width: 180px; margin-left: auto; margin-right: auto; display: block; padding-top: 20px; padding-bottom:20px;' />
<div class="heading">
<center>Dashboard</center>
</div>
<div class="form">
<form action ="home.html" class="register-form">
<input type="text" placeholder="name"/>
<input type="password" placeholder="password"/>
<input type="text" placeholder="email address"/>
<button>create</button>
<p class="message">Already registered? <a href="#">Sign In</a></p>
</form>
<form action="home.html" class="login-form">
<input type="text" placeholder="username"/>
<input type="password" placeholder="password"/>
<button id="button_login">login</button>
<p class="message">Not registered? <a href="#">Create an account</a></p>
</form>
</div>
</div>
</body>
</html>
如何使用我的自定义登录页面代替Spring Security的登录页面显示?
回答:
参见Spring Security Reference:
虽然自动生成的登录页面便于快速启动和运行,但是大多数应用程序都希望提供自己的登录页面。为此,我们可以如下所示更新配置:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login") 1
.permitAll(); 2
}
更新的配置指定登录页面的位置。
我们必须授予所有用户(即未经身份验证的用户)访问我们登录页面的权限。formLogin()。permitAll()方法允许向所有用户授予与基于表单的登录相关联的所有URL的访问权限。
您修改的代码:
public void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity
.authorizeRequests()
.antMatchers("/home*").hasRole("USER")
.and()
.formLogin()
.loginPage("/login.html")
.permitAll();
}
以上是 如何使用Spring Security自定义登录页面? 的全部内容, 来源链接: utcz.com/qa/410438.html