首页 > 其他分享 >Springboot 配置 Security流程

Springboot 配置 Security流程

时间:2022-11-19 01:22:36浏览次数:46  
标签:Springboot 流程 java1234 springframework org import Security com security

装入依赖

引入spring-sercurity

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

编写配置文件

package com.java1234.config;

import com.java1234.common.security.LoginFailedHandler;
import com.java1234.common.security.LoginSucessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.config.http.SessionCreationPolicy;

/**
 * spring security配置
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private LoginSucessHandler loginSucessHandler;

    @Autowired
    private LoginFailedHandler loginFailedHandler;

    private static final String URL_WHITELIST[] = {"/login", "/logout", "/user/captcha", "/password", "/image/**", "/test/**"};

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 开启跨域 和 csrf攻击 关闭
        http
                .cors()
                .and()
                .csrf()
                .disable()
        // 登录配置
                .formLogin()
         .successHandler(loginSucessHandler)
         .failureHandler(loginFailedHandler)
        // .and()
        // .logout()
        // .logoutSuccessHandler()
        // session禁用配置
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        // 拦截规则配置
                .and()
                .authorizeRequests()
                .antMatchers(URL_WHITELIST).permitAll()
                .anyRequest().authenticated();
        // 异常处理器配置
        // 自定义过滤器配置
    }

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

登录成功逻辑实现

package com.java1234.common.security;

import com.alibaba.druid.support.json.JSONUtils;
import com.java1234.common.constant.MsgConstant;
import com.java1234.entity.R;
import com.java1234.utils.JwtUtils;
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.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utc-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        String username = "user";
        String token = JwtUtils.genJwtToken(username);
        outputStream.write(JSONUtils.toJSONString((R.ok(MsgConstant.LOGIN_SUCCESS).put("authorization",token))).getBytes());//将数据转换成json字符串写入到输出流中
        outputStream.flush();//发送数据到前端
        outputStream.close();
    }
}

登录失败逻辑

package com.java1234.common.security;

import com.alibaba.druid.support.json.JSONUtils;
import com.java1234.entity.R;
import org.springframework.security.authentication.BadCredentialsException;
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;
import java.io.OutputStream;

@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        OutputStream outputStream = httpServletResponse.getOutputStream();
        String message = e.getMessage();
        if(e instanceof BadCredentialsException) {
            message = "用户名或者密码错误";
        }
        outputStream.write(JSONUtils.toJSONString(R.error(message)).getBytes());
        outputStream.flush();
        outputStream.close();
    }
}

标签:Springboot,流程,java1234,springframework,org,import,Security,com,security
From: https://www.cnblogs.com/guozhiqiang/p/16905342.html

相关文章

  • SpringBoot整合JUnit
    这个不用自己整合,在创建好SpringBoot项目后在Test文件夹中就能找到,相关的依赖也导入进去了。这里只是进行一个详细的说明。  @SpringBootTest类型:测试类注解位置:测......
  • SQL基础篇(一)---JOIN语句执行流程&ON与WHERE的区别
    本文主要记录了MySQL中的JOIN语句具体执行流程,同时分析了ON与WHERE条件的区别。1.执行流程一个完整的SQL语句中会被拆分成多个子句,子句的执行过程中会产生......
  • springboot+minio实现分片上传(超大文件快速上传)
    ​ 设计由来在实际的项目开发中常遇到超大附件上传的情况,有时候客户会上传GB大小的文件,如果按照普通的MultipartFile方式来接收上传的文件,那么无疑会把服务器给干崩......
  • 2022最简单易懂的IOS App打包发布完整流程
    创建appid标识符进入​​apple开发者中心​​点击Account编辑切换为居中添加图片注释,不超过140字(可选)点击Certificates,Identifiers&Profiles,创建AppIDS标识符,点击左......
  • 2022最新iOS最新打包发布流程
     关于如何发布iOS应用到AppStroe,苹果开发者中心已经给出了很详细的说明。和普通的iOS应用一样,使用ReactNative开发的iOS应用也需要使用普通的iOS应用的发布流程,总的来......
  • 2022超详细流程ios APP最新打包上线教程,保证一看就会!
     这篇文章主要是想要给大家讲述一下APP打包上线到APPStore的详细流程。作为一名开发人员,上架APP是必须要会的,否则出去都不好意思说自己是iOS程序员。而且上线过APP的小......
  • 2022最简单易懂的IOS App打包发布完整流程
     创建appid标识符进入apple开发者中心点击Account​编辑切换为居中添加图片注释,不超过140字(可选)点击Certificates,Identifiers&Profile......
  • 2022超详细流程ios APP最新打包上线教程,保证一看就会!
    这篇文章主要是想要给大家讲述一下APP打包上线到APPStore的详细流程。作为一名开发人员,上架APP是必须要会的,否则出去都不好意思说自己是iOS程序员。而且上线过APP的小伙伴......
  • 框架进行时——SpringMVC流程简析(一)
    基于SpringWeb(5.3.23)的接口请求分析前情提要假定当前Web项目中有如下实体类和接口:packagecom.example.entity;publicclassWebUser{privateStringname;......
  • SpringBoot提供的三种配置文件格式
    1、application.properties(传统格式/默认格式)e.g.server.port=80 2、application.yml(主流格式、推荐使用)e.g.server:  port:81 3、application.yamle.g.ser......