Spring Security - Spring Security表单认证

默认表单认证

创建一个包configuration用于存放一些通用配置

创建类WebSecurityConfig继承WebSecurityConfigurerAdapter

image-20201014104845465.png

添加@EnableWebSecurity注解,使其被spring发现注册

WebSecurityConfigurerAdapter类对configure(HTTPSecurity http)的定义

//使用默认配置(HttpSecurity)。如果子类化,则可能会重写子类configure(HttpSecurity)
protected void configure(HttpSecurity http) throws Exception {
 this.logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");
 ((HttpSecurity)((HttpSecurity)((AuthorizedUrl)http.authorizeRequests().anyRequest()).authenticated().and()).formLogin().and()).httpBasic();
 }

可以看出WebSecurityConfigurerAdapter已经默认声明了一些安全特性

  • .anyRequest()验证所有请求

  • .formLogin()允许用户使用表单登录进行身份验证(Spring Security 默认自带一个简单的登录验证页面)

  • .httpBasic()允许用户使用HTTP基本认证

重新启动项目

访问http://localhost:8080/hi

自动跳转到默认表单登录页http://localhost:8080/login

输入用户名密码

跳回原来访问地址

自定义表单登录页

使用自己定义的表单登录页

重写configure方法

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
​
 @Override
 protected void configure(HttpSecurity http) throws Exception {
 http.authorizeRequests()
 .anyRequest()
 .authenticated()
 .and()
 .formLogin()
 .loginPage("/myLogin.html")
 // 使登录页面不设限访问
 .permitAll()
 .and()
 .csrf().disable();
​
 }
}

HttpSecurity被设计为链式调用,在执行每一个方法后,都会返回一个预期的上下文,便于连续调用。

重启项目

访问http://localhost:8080/hi

路径跳转http://localhost:8080/myLogin.html(自定义的登录页面地址)

编写自定义页面代码

<!doctype html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport"
 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>登录</title>
</head>
<body>
<div class="main">
 <div class="title">
 <span>密码登录</span>
 </div>
​
 <div class="title-msg">
 <span>请输入登录账户和密码</span>
 </div>
​
 <form class="login-form" action="/myLogin.html" method="post" novalidate>
 <!--输入框-->
 <div class="input-content">
 <!--autoFocus-->
 <div>
 <input type="text" autocomplete="off"
 placeholder="用户名" name="username" required/>
 </div>
​
 <div style="margin-top: 16px">
 <input type="password"
 autocomplete="off" placeholder="登录密码" name="password" required maxlength="32"/>
 </div>
 </div>
​
 <!--登入按钮-->
 <div style="text-align: center">
 <button type="submit" class="enter-btn">登录</button>
 </div>
​
 <div class="foor">
 <div class="left"><span>忘记密码 ?</span></div>
​
 <div class="right"><span>注册账户</span></div>
 </div>
 </form>
</div>
</body>
<style>
 body {
 background: #353f42;
 }
​
 * {
 padding: 0;
 margin: 0;
 }
​
 .main {
 margin: 0 auto;
 padding-left: 25px;
 padding-right: 25px;
 padding-top: 15px;
 width: 350px;
 height: 350px;
 background: #FFFFFF;
 /*以下css用于让登录表单垂直居中在界面,可删除*/
 position: absolute;
 top: 50%;
 left: 50%;
 margin-top: -175px;
 margin-left: -175px;
 }
​
 .title {
 width: 100%;
 height: 40px;
 line-height: 40px;
 }
​
 .title span {
 font-size: 18px;
 color: #353f42;
 }
​
 .title-msg {
 width: 100%;
 height: 64px;
 line-height: 64px;
 }
​
 .title:hover {
 cursor: default;
 }
​
 .title-msg:hover {
 cursor: default;
 }
​
 .title-msg span {
 font-size: 12px;
 color: #707472;
 }
​
 .input-content {
 width: 100%;
 height: 120px;
 }
​
 .input-content input {
 width: 330px;
 height: 40px;
 border: 1px solid #dad9d6;
 background: #ffffff;
 padding-left: 10px;
 padding-right: 10px;
 }
​
 .enter-btn {
 width: 350px;
 height: 40px;
 color: #fff;
 background: #0bc5de;
 line-height: 40px;
 text-align: center;
 border: 0px;
 }
​
 .foor {
 width: 100%;
 height: auto;
 color: #9b9c98;
 font-size: 12px;
 margin-top: 20px;
 }
​
 .enter-btn:hover {
 cursor: pointer;
 background: #1db5c9;
 }
​
 .foor div:hover {
 cursor: pointer;
 color: #484847;
 font-weight: 600;
 }
​
 .left {
 float: left;
 }
​
 .right {
 float: right;
 }
</style>
</html>

通过from表单POST方式,提交usernamepassword/myLogin.html

将该页面放置在resources/static/下,重启项目

访问http://localhost:8080/hi

跳转到以下页面

image-20201014142724675.png

输入自定义的用户名密码

跳转成功,返回之前访问页面http://localhost:8080/hi

loginProcessingUrl自定义登录请求URL

默认处理登录请求的URL/login

我们可以通过配置去修改这个URL

@Override
 protected void configure(HttpSecurity http) throws Exception {
 http.authorizeRequests()
 .anyRequest()
 .authenticated()
 .and()
 .formLogin()
 .loginPage("/myLogin.html")
 // 指定处理登录请求的路径,修改请求的路径,默认为/login
 .loginProcessingUrl("/mylogin")
 // 使登录页面不设限访问
 .permitAll()
 .and()
 .csrf().disable();​
 }

同时form表单请求的action属性需要同步修改为/mylogin

在前后分离的项目中,当登录请求发送成功后,一般会由后端返回一串JSON报文,前端根据返回报文,判断是否登录成功,之后跳转到哪个页面。

SpringSecurity通过配置同样可以实现

  • successHandler()

    • 处理登录成功后的逻辑

    • Authentication携带用户名以及角色等信息

  • failureHandler()

    • 处理登录失败后的逻辑

    • AuthenticationException携带异常信息

 @Override
 protected void configure(HttpSecurity http) throws Exception {
 http.authorizeRequests()
 .anyRequest()
 .authenticated()
 .and()
 .formLogin()
 .loginPage("/myLogin.html")
 // 指定处理登录请求的路径,修改请求的路径,默认为/login
 .loginProcessingUrl("/mylogin")
 // 登录成功后处理逻辑
 .successHandler(new AuthenticationSuccessHandler() {
 @Override
 public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
 httpServletResponse.setContentType("application/json;charset=UTF-8");
 PrintWriter out = httpServletResponse.getWriter();
 out.write("{\n" +
 "    \"error_code\": 0,\n" +
 "    \"message\": \"欢迎登录\"\n" +
 "}");
 }
 })
 // 登录失败后处理逻辑
 .failureHandler(new AuthenticationFailureHandler() {
 @Override
 public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
 httpServletResponse.setContentType("application/json;charset=UTF-8");
 httpServletResponse.setStatus(401);
 PrintWriter out = httpServletResponse.getWriter();
 out.write("{\n" +
 "    \"error_code\": 401,\n" +
 "    \"message\": \"请求失败,"+ e.getMessage() +"\"\n" +
 "}");
 }
 })
 // 使登录页面不设限访问
 .permitAll()
 .and()
 .csrf().disable();
​
 }

以上通过自定义表单实现了Spring Security的表单认证功能。但是实际开发中用户名和密码都是来自于数据库,并且用户还包含角色等信息。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。