spring boot整合SpringSecurity 目录

spring boot整合SpringSecurity-01入门
spring boot整合SpringSecurity-02 基于Serssion的认证
spring boot整合SpringSecurity-03 自定义报错信息
spring boot整合SpringSecurity-04 使用jwt的方式认证

自定义报错信息

当我们没有配置报错信息,报错信息是这样的。

这样的报错信息并不是我们想要的。这个时候就需要我们自己定义报错信息。

配置文件信息

package com.hnbd.jinshui.config;import com.hnbd.jinshui.security.handler.JWTAccessDeniedHandler;
import com.hnbd.jinshui.security.handler.JWTAuthenticationEntryPoint;
import com.hnbd.jinshui.security.handler.JwtLogoutSuccessHandler;
import com.hnbd.jinshui.service.UserDetailsServiceImpl;
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.crypto.bcrypt.BCryptPasswordEncoder;/*** SecurityConfig    登录认证的配置** @创建人 江枫沐雪* @创建时间 2021/6/20 17:17*/
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserDetailsServiceImpl userDetailsService;@Autowiredprivate BCryptPasswordEncoder bCryptPasswordEncoder;//查询用户信息@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//用户详情信息auth.userDetailsService(userDetailsService)//密码加密方式.passwordEncoder(bCryptPasswordEncoder);}//安全拦截机制@Overrideprotected void configure(HttpSecurity http) throws Exception {// @formatter:off//配置跨域请求 并且 关闭打开的csrf保护http .cors().and().csrf().disable()
//                 认证配置.authorizeRequests()
//                 登录验证等放行.antMatchers("/auth/**","/app/**").permitAll()
//                 剩下的接口都需要登陆后访问.anyRequest().authenticated().and()//表单登录.formLogin()
//                   用户未登录的的时候跳转的这个路径
//                    .loginPage("/home")
//                   用户登录时,用户名、密码提交的目的路径.loginProcessingUrl("/login")
//                   用户成功登录以后.successForwardUrl("/success").and().logout().logoutUrl("/logout")// 退出成功后返回.logoutSuccessHandler(new JwtLogoutSuccessHandler()).and()
//                   异常处理.exceptionHandling()
//                   没有登录,返回.authenticationEntryPoint(new JWTAuthenticationEntryPoint())
//                   添加无权限时的处理.accessDeniedHandler(new JWTAccessDeniedHandler());}
}

退出时返回的数据。

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** 退出成功处理器* @创建人 江枫沐雪* @创建时间 2021/8/1 15:00*/
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {@Overridepublic void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)throws IOException, ServletException {// 返回结果   字符集编码response.setCharacterEncoding("UTF-8");//  设置内容类型response.setContentType("application/json; charset=utf-8");
//      response.getWriter().append(JSONConverter.toJSON(ApiResponseWithData.ofSuccess("成功推出")));//返回的信息response.getWriter().append("成功推出");}}

没有登录

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** 没有登录* @创建人 江枫沐雪* @创建时间 2021/8/1 15:00*/
public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {@Overridepublic void commence(HttpServletRequest request, HttpServletResponse response,AuthenticationException authException) throws IOException, ServletException {response.setCharacterEncoding("UTF-8");response.setContentType("application/json; charset=utf-8");
//      response.getWriter().write(JSONConverter.toJSON(ApiResponse.ofStatus(ApiResponseStatus.INVALID_TOKEN)));response.getWriter().append("没有登录");}
}

无权访问结果

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** 无访问权限处理器** @创建人 江枫沐雪* @创建时间 2021/8/1 15:00*/
public class JWTAccessDeniedHandler implements AccessDeniedHandler {@Overridepublic void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {//设置字符编码request.setCharacterEncoding("UTF-8");//设置内容类型response.setContentType("application/json; charset=utf-8");response.getWriter().append("没有权限");
//        httpServletResponse.getWriter()
//                .write(JSONConverter.toJSON(ApiResponse.ofStatus(ApiResponseStatus.NO_PERMISSION)));}
}

spring boot整合SpringSecurity-03 自定义报错信息相关推荐

  1. spring cloud整合feign和nacos报错:No Feign Client for loadBalancing defined. Did you forget to include

    Did you forget to include spring-cloud-starter-loadbalancer 问题描述 项目环境 解决方案 1.引入eureka依赖--无效 2.降低spri ...

  2. [初学Spring Boot](2):单元测试报错:org.junit.runners.model.InvalidTestClassError:Invalid test class

    本来: 是建项目时自动生成的测试类,结果还是报错了.大无语事件. 就是IDEA自建测试时导错包了. 注释掉的时原来自导的,换成短的就好了. 经查证,长的是升级版,junit5,spring boot版 ...

  3. spring boot多数据库数据源启动报错“required a single bean, but 2 were found”的正确解决办法

    报错 Parameter 0 of method jdbcTemplate in org.springframework.boot.autoconfigure.jdbc.JdbcTemplateCon ...

  4. spring boot访问Druid控制台页面报错 Sorry, you are not permitted to view this page.

    1.报错如下图: 2.配置如下: spring:datasource:type: com.alibaba.druid.pool.DruidDataSourcedruid:driver-class-na ...

  5. idea创建spring boot项目初始时pom报错解决

    问题:idea创建springboot项目时,刚创建完成还未配置pom文件时,pom大量报错 解决: 步骤一,在pom的build段加入版本号,该版本号与boot版本号一致 <build> ...

  6. spring boot打包文件后,报错\No such file or directory

    现象: 一段代码: ClassLoader loader = XXXUtil.class.getClassLoader();String jsFileName = loader.getResource ...

  7. spring boot创建新工程运行报错解决方案

    [问题出现原因] 问题出现在创建spring Initializr创建新工程时选择myBatis问题. 该类问题一般出现在application.properties配置文件问题. 选择对应的mysq ...

  8. spring boot整合jsp报错 Whitelabel Error Page 500或者404 问题处理

    在刚刚用idea创建的spring boot 项目整合jsp时, 一直不能正常访问,报错信息如下图 There was an unexpected error (type=Internal Serve ...

  9. 【学习之路】spring boot 整合mybatis报错 “serverTimezone=UTC“

    目录 一.踩坑原因 二.踩坑之前 三.报错原因 四.解决过程 方案一 方案二 方案三 方案四 方案五(重点) 结束 PS 一.踩坑原因 在学习spring boot 整合 mybatis-gegera ...

最新文章

  1. [裴礼文数学分析中的典型问题与方法习题参考解答]5.1.21
  2. gstreamer 获取帧数据_Android App卡顿率(顺滑度、顺滑度)并整理数据
  3. python右对齐格式化输出_python笔记-格式化输出(%和format的用法)
  4. 【通知】有三AI项目研发组成员招收条件及可对接业务暂行方案
  5. Python字典(dict )的几种遍历方式
  6. [Qt教程] 第44篇 进阶(四)信号和槽
  7. win7电脑共享硬盘分区的方法
  8. 亚马逊无人超市Amazon Go这次是真的真的开业了
  9. JDBC 与ODBC的区别
  10. java pingfang,PingFang sc字体的使用
  11. 发那科机器人编程软件fanuc roboguide授权补丁_工业机器人离线编程与应用:ROBOGUIDE V8.3版本的工程文件创建...
  12. 2021“华为杯”第十八届中国研究生数学建模竞赛有感
  13. 学科实践活动感悟50字_学科实践活动写实记录50字3篇
  14. 信息学奥赛一本通C++语言-----1120:同行列对角线的格
  15. 短期怎么学会云计算?新手学习云计算的规划
  16. S32K144时钟配置
  17. pdf转图片在线转换怎么转?分享一个转换技巧
  18. c语言笔记——黑马程序员上课笔记
  19. 毕业晚会主题八个字计算机学院,毕业主题标语8个字
  20. 2022年下半年软考考科目有这些,快看

热门文章

  1. 在 .NET 7上使用 WASM 和 WASI
  2. React用户安全的第一道防线
  3. 逾百位开发者到场,超 2 万人线上观看!龙蜥社区开发者服务 devFree MeetUp 精彩回顾来啦
  4. php导出1万条数据excel_实用!用PHP导出百万级大数据到Excel
  5. 微信公众平台--提升篇
  6. ubuntu不能联网
  7. 个人项目总结------珠宝管理系统
  8. react——props和高阶组件
  9. 信息熵、交叉熵公式的理解
  10. 微信小程序禁用页面滚动的几种方式