spring boot 之 security(二) 基于表单的认证

一、自定义登陆页面,并登陆

在 WebSecurityConfig 中更改配置,如果不知道我改了什么,请到 spring boot 之 security(一) 对比。

package com.wt.cloud.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * 功能描述: WebSecurityConfigurerAdapter web安全应用的适配器
 * @author : big uncle
 * @date : 2019/10/10 10:26
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭默认的basic认证拦截
//        http
//        .authorizeRequests()
//        .anyRequest()
//        .permitAll().and()
//        .logout()
//        .permitAll();
        // 让使用form表单认证
        http.formLogin()
                // 自定义登陆页面
                .loginPage("/login.html")
                // 覆盖spring security默认登陆地址。默认是login
                .loginProcessingUrl("/auth/login")
                .and()
                // 以下都是授权的配置
                .authorizeRequests()
                // 剔除登陆页面的认证拦截,否则会在进登陆页面一直跳转;permitAll 指任何人都可以访问这个url
                .antMatchers("/login.html","/auth/login").permitAll()
                // 任何请求
                .anyRequest()
                // 都需要身份认证
                .authenticated()
                .and()
                // 关闭跨站请求伪造拦截
                .csrf().disable();
    }
}

loginProcessingUrl 这个要跟大家单独说下,这个是覆盖spring security的默认登陆地址,也可以在我 spring boot 之 security(一) 中查看 security 的核心及原理,他会被第一层过滤器拦截 UsernamePasswordAuthenticationFilter,而想要正确被拦截,要么使用默认,要么自己覆盖。
然后新建一个login.html

login.html

内容大致如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/auth/login" method="post">
        <input name="username"> 姓名
        <br>
        <input name="password"> 密码
        <br>
        <input type="submit" value="登陆" >
    </form>
</body>
</html>

二、前后端分离怎么办

前后端分离逻辑图

前后端分离只能给的是状态码,那我们应该怎么处理呢...
只需要把 WebSecurityConfig 中的 loginPage 配置我们自定义的 controller 即可

WebSecurityConfig
 package com.wt.cloud.config;

import com.wt.cloud.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * 功能描述: WebSecurityConfigurerAdapter web安全应用的适配器
 * @author : big uncle
 * @date : 2019/10/10 10:26
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭默认的basic认证拦截
//        http
//        .authorizeRequests()
//        .anyRequest()
//        .permitAll().and()
//        .logout()
//        .permitAll();
        // 让使用form表单认证
        http.formLogin()
                // 自定义登陆页面
                .loginPage("/web/authentication")
                // 覆盖spring security默认登陆地址。默认是login
                .loginProcessingUrl("/authentication/login")
                .and()
                // 以下都是授权的配置
                .authorizeRequests()
                // 剔除登陆页面的认证拦截,否则会在进登陆页面一直跳转;permitAll 指任何人都可以访问这个url
                .antMatchers("/web/authentication",securityProperties.getWebProperties().getLoginPage()).permitAll()
                // 任何请求
                .anyRequest()
                // 都需要身份认证
                .authenticated()
                .and()
                // 关闭跨站请求伪造拦截
                .csrf().disable();

    }
}
自定义的controller
package com.wt.cloud.web;

import cn.hutool.core.util.StrUtil;
import com.wt.cloud.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/web")
@Slf4j
public class WebController {

    /**
     * 自定义的一些配置信息,如登陆页面等
     */
    @Autowired
    private SecurityProperties securityProperties;
    /**
     * 缓存了当前的请求
     */
    private RequestCache requestCache = new HttpSessionRequestCache();

    /**
     *
     */
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    /**
     * 功能描述: 当需要身份认证时 跳转到这里
     * @author : big uncle
     * @date : 2019/10/12 12:18
     */
    @GetMapping("/authentication")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public String requireAuthenrication(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SavedRequest savedRequest = requestCache.getRequest(request,response);
        if(savedRequest!=null){
            String url = savedRequest.getRedirectUrl();
            log.debug("引发的请求是 {}",url);
            if(StrUtil.endWithIgnoreCase(url,".html")){
                redirectStrategy.sendRedirect(request,response,securityProperties.getWebProperties().getLoginPage());
            }
        }
        return "没有登陆,请登录";
    }
}

三、自定义登陆成功处理

为什么要有自定义成功处理,因为现代都是前后端分离项目,spring 默认的是登陆成功跳转,我们不可能给前端跳转,所以我们自己处理登陆成功,响应登陆成功的json结果给前端。
自定义登陆成功需要实现 AuthenticationSuccessHandler 重写 onAuthenticationSuccess 方法。

自定义成功处理类
package com.wt.cloud.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 功能描述: 成功处理器
 * @author : big uncle
 * @date : 2019/10/12 14:18
 */
@Component
@Slf4j
public class MyAuthenticationSuccessHandle implements AuthenticationSuccessHandler {


    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 功能描述: Authentication 封装用户的认证信息,ip,session,userDetail等
     * @author : big uncle
     * @date : 2019/10/12 14:13
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(authentication));
        log.debug("登陆成功");
    }

    /**
     * authentication 所包含信息
     * {
     *  "authorities": [{ // 权限
     *      "authority": "admin"
     *        }],
     *  "details": {
     *      "remoteAddress": "0:0:0:0:0:0:0:1",
     *      "sessionId": null
     *    },
     *  "authenticated": true, // 认证通过
     *  "principal": { // userDetail的信息
     *      "password": null,
     *      "username": "admin",
     *      "authorities": [{
     *          "authority": "admin"
     *        }],
     *      "accountNonExpired": true,
     *      "accountNonLocked": true,
     *      "credentialsNonExpired": true,
     *      "enabled": true
     *    },
     *  "credentials": null,
     *  "name": "admin"
     * }
     */

}

在 WebSecurityConfig 配置,先注入 MyAuthenticationSuccessHandle,在 formLogin 中再加 .successHandler(myAuthenticationSuccessHandle) 即可

四、自定义登陆失败处理

失败的配置和成功其实是一样的,只是实现的类换了 AuthenticationFailureHandler

失败自定义类
package com.wt.cloud.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("登陆失败");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.getWriter().write("o failure");
    }

}

WebSecurityConfig 的配置
package com.wt.cloud.config;

import com.wt.cloud.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * 功能描述: WebSecurityConfigurerAdapter web安全应用的适配器
 * @author : big uncle
 * @date : 2019/10/10 10:26
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private MyAuthenticationSuccessHandle myAuthenticationSuccessHandle;
    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭默认的basic认证拦截
//        http
//        .authorizeRequests()
//        .anyRequest()
//        .permitAll().and()
//        .logout()
//        .permitAll();
        // 让使用form表单认证
        http.formLogin()
                // 自定义登陆页面
                .loginPage("/web/authentication")
                // 覆盖spring security默认登陆地址。默认是login
                .loginProcessingUrl("/authentication/login")
                // 配置成功处理类
                .successHandler(myAuthenticationSuccessHandle)
                // 配置失败处理类
                .failureHandler(myAuthenticationFailureHandler)
                .and()
                // 以下都是授权的配置
                .authorizeRequests()
                // 剔除登陆页面的认证拦截,否则会在进登陆页面一直跳转;permitAll 指任何人都可以访问这个url
                .antMatchers("/web/authentication",securityProperties.getWebProperties().getLoginPage()).permitAll()
                // 任何请求
                .anyRequest()
                // 都需要身份认证
                .authenticated()
                .and()
                // 关闭跨站请求伪造拦截
                .csrf().disable();

    }
}
不是前端分离的改造

如果不是前端分离,则可以把 成功处理器 和 失败处理器的 实现 改成 继承,成功继承 SavedRequestAwareAuthenticationSuccessHandler,失败继承 SimpleUrlAuthenticationFailureHandler

成功
package com.wt.cloud.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 功能描述: 成功处理器
 * @author : big uncle
 * @date : 2019/10/12 14:18
 */
@Component
@Slf4j
public class MyAuthenticationSuccessHandle extends SavedRequestAwareAuthenticationSuccessHandler {

    @Value("${cloud.web.dataType}")
    private String dataType;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 功能描述: Authentication 封装用户的认证信息,ip,session,userDetail等
     * @author : big uncle
     * @date : 2019/10/12 14:13
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 判断是否以json的形式给前端数据,还是直接跳转到成功页面
        if(dataType.equalsIgnoreCase("json")) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        }else{
            // 实现跳转
            super.onAuthenticationSuccess(request,response,authentication);
        }
        log.debug("登陆成功");
    }

    /**
     * authentication 所包含信息
     * {
     *  "authorities": [{ // 权限
     *      "authority": "admin"
     *        }],
     *  "details": {
     *      "remoteAddress": "0:0:0:0:0:0:0:1",
     *      "sessionId": null
     *    },
     *  "authenticated": true, // 认证通过
     *  "principal": { // userDetail的信息
     *      "password": null,
     *      "username": "admin",
     *      "authorities": [{
     *          "authority": "admin"
     *        }],
     *      "accountNonExpired": true,
     *      "accountNonLocked": true,
     *      "credentialsNonExpired": true,
     *      "enabled": true
     *    },
     *  "credentials": null,
     *  "name": "admin"
     * }
     */

}

失败
package com.wt.cloud.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 功能描述: 处理失败器
 * @author : big uncle
 * @date : 2019/10/12 14:54
 */
@Component
@Slf4j
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Value("${cloud.web.dataType}")
    private String dataType;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 判断是否以json的形式给前端数据,还是直接跳转到失败页面
        if(dataType.equalsIgnoreCase("json")) {

            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.getWriter().write(exception.getMessage());
        }else {
            super.onAuthenticationFailure(request,response,exception);
        }
        log.info("登陆失败");
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,699评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,124评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,127评论 0 358
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,342评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,356评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,057评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,654评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,572评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,095评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,205评论 3 339
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,343评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,015评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,704评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,196评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,320评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,690评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,348评论 2 358

推荐阅读更多精彩内容