【问题】网站 项目里经常用到DateTime类型变量,要求所有日期时间类型格式标准为“yyyy-MM-dd HH:mm:ss”,但默认Tostring格式为 yyyy-M-d H:m:s ,没有前置0, 需要修改 【分析】 1、修改代码里所有DateTime类型的Tostring为 ToString("yyyy-MM-dd HH:mm:ss"),不方便 2、找见统一的修改地方, Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-CN", true) { DateTimeFormat = { ShortDatePattern = "yyyy-MM-dd", FullDateTimePattern = "yyyy-MM-dd HH:mm:ss" }; 发现不起作用 经分析DateTimeFormat 类的属性,发现 LongTimePattern 起作用 【结论】 增加 LongTimePattern 属性
1 2 3 |
Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-CN", true) { DateTimeFormat = { ShortDatePattern = "yyyy-MM-dd", FullDateTimePattern = "yyyy-MM-dd HH:mm:ss", LongTimePattern ="HH:mm:ss"} }; |
from:https://blog.csdn.net/onemetre/article/details/52042907
View Details1、从微软下载net core https://download.visualstudio.microsoft.com/download/pr/dd164132-d4c4-4c1a-8233-a4fc7e157935/bffa5312d613cab1a14f0858f947a6fc/dotnet-runtime-2.1.11-linux-x64.tar.gz 2、将安装包上传至linux中 3、解压 tar -vxf dotnet-runtime-2.1.11-linux-x64.tar.gz 4、创建链接,使所有目录下都可以访问到dotnet命令(这里是解压后放在/home/dotnetcore目录下) ln -s /home/dotnetcore/dotnet /usr/local/bin 5、测试验证是否成功 任意目录下:dotnet --info 最后,使用dotnet+dll名称,测试软件是否可以运行,如果无法运行,则安装相应的软件包即可 参考: 1、.NET Core 指南:https://docs.microsoft.com/zh-cn/dotnet/core/ 2、net core下载中心:https://dotnet.microsoft.com/download/dotnet-core from:https://blog.csdn.net/dqcoffee/article/details/91353543
View Details在部署的时候,如果您不想在您的Linux服务器上安装.Net Core SDK,您可以只安装Runtime,接下来我们看看该如何安装运行时Runtime。 下载运行时文件 下载页面:https://www.microsoft.com/net/download/linux 先获取一下对应的下载链接,可以使用浏览器点击链接来获取具体文件的下载链接 获取完链接以后,就可以使用命令下获取和安装了 以Centos 7,Ubuntu 16.04为例安装ASP.Net Core 2.0.5的运行时:
1 2 3 4 5 |
wget -O dotnet-runtime.tar.gz https://download.microsoft.com/download/1/1/0/11046135-4207-40D3-A795-13ECEA741B32/dotnet-runtime-2.0.5-linux-x64.tar.gz wget -O aspnetcore-store.tar.gz https://download.microsoft.com/download/1/1/0/11046135-4207-40D3-A795-13ECEA741B32/aspnetcore-store-2.0.5-linux-x64.tar.gz mkdir dotnet tar zxf dotnet-runtime.tar.gz -C dotnet tar zxf aspnetcore-store.tar.gz -C dotnet |
还需要安装 libunwind Centos 7
1 |
yum update -y && yum install libunwind libicu -y |
Ubuntu 16.04
1 |
apt-get update -y && apt-get install libunwind-dev -y |
原文地址:https://www.zkea.net/codesnippet/detail/post-85 from:https://www.cnblogs.com/seriawei/p/8438126.html
View Details最近在技术博客和技术交流群遇到很多小伙伴们在Linux下更新或者安装.Net Core SDK后dotnet命令无法识别等问题,现如下解决: 卸载SDK命令
1 |
sudo yum remove dotnet-sdk-* |
1 |
sudo yum remove libunwind libicu |
1 |
sudo yum remove /etc/yum.repos.d/dotnetdev.repo |
从新安装即可 from:https://www.cnblogs.com/yangzhili/p/9217083.html
View Details
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
2019-05-09 10:27:01,330 线程ID:[80] 日志级别:ERROR 出错类:WebApp.HttpGlobalExceptionFilter property:[(null)] - 错误描述:System.TypeInitializationException: The type initializer for 'System.DrawingCore.GDIPlus' threw an exception. ---> System.DllNotFoundException: Unable to load shared library 'gdiplus' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: libgdiplus: cannot open shared object file: No such file or directory at System.DrawingCore.GDIPlus.GdiplusStartup(UInt64& token, GdiplusStartupInput& input, GdiplusStartupOutput& output) at System.DrawingCore.GDIPlus..cctor() --- End of inner exception stack trace --- at System.DrawingCore.GDIPlus.GdipGetGenericFontFamilySansSerif(IntPtr& fontFamily) at System.DrawingCore.FontFamily..ctor(GenericFontFamilies genericFamily) at System.DrawingCore.FontFamily.get_GenericSansSerif() at System.DrawingCore.Font.CreateFont(String familyName, Single emSize, FontStyle style, GraphicsUnit unit, Byte charSet, Boolean isVertical) at Common.VerifyCodeHelper.CreateByteByImgVerifyCode(String verifyCode, Int32 width, Int32 height) in F:\src\WebApp\Common\VerifyCodeHelper.cs:line 206 at WebApp.Controllers.VerifyCodeController.NumberVerifyCode() in F:\src\WebApp\Controllers\VerifyCodeController.cs:line 27 at lambda_method(Closure , Object , Object[] ) at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters) at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextExceptionFilterAsync() |
解决方法 Centos 7 yum install libgdiplus-devel from:https://www.cnblogs.com/asd14828/p/10837140.html?utm_source=tuicool
View Details通过 Opw.HttpExceptions.AspNetCore 搞定了。 1)安装 nuget 包 Opw.HttpExceptions.AspNetCore
1 |
<PackageReference Include="Opw.HttpExceptions.AspNetCore" Version="2.3.0" /> |
2)Startup.ConfigureServices 中添加 AddHttpExceptions
1 |
services.AddControllers().AddHttpExceptions(); |
3)Startup.Configure 中添加 UseHttpExceptions
1 |
app.UseHttpExceptions(); |
示例响应输出
1 |
{"type":"error:invalid-cast","title":"InvalidCast","status":500,"detail":"Invalid cast from \u0027System.Int32\u0027 to \u0027Cnblogs.Infrastructure.Primitives.PostConfig\u0027.","instance":"/zzkdocuments"} |
from:https://q.cnblogs.com/q/121590/
View Details改单个项目 在项目的build.gradle文件中,修改repositories配置,将mavenCentral()改为 maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/'}, 如:
1 2 3 |
repositories { maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' } } |
更改所有项目 如果想一次更改所有的仓库地址,可以在 USER_HOME/.gradle/文件夹下添加 init.gradle 文件来配置,如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
allprojects{ repositories { def REPOSITORY_URL = 'http://maven.aliyun.com/nexus/content/groups/public/' all { ArtifactRepository repo -> if(repo instanceof MavenArtifactRepository){ def url = repo.url.toString() if (url.startsWith('https://repo1.maven.org/maven2') || url.startsWith('https://jcenter.bintray.com/')) { remove repo } } } maven { url REPOSITORY_URL } } } |
作者:xiaolyuh 链接:https://www.jianshu.com/p/471227b2b7e8 来源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
View Details问题描述 使用swagger生成接口文档后,访问http://localhost:8888/swagger-ui.html#/,显示如下: 有些强迫症的我,感觉看起来很不舒服,结果百度了好久,找到解决方案,刚接触spring boot对于很多api还不是很熟悉,先mark再说 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package com.course.config; import com.google.common.base.Predicates; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .pathMapping("/") .select() // 选择那些路径和api会生成document .apis(RequestHandlerSelectors.any())// 对所有api进行监控 //不显示错误的接口地址 .paths(Predicates.not(PathSelectors.regex("/error.*")))//错误路径不监控 .paths(PathSelectors.regex("/.*"))// 对根下所有路径进行监控 .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder().title("这是我的接口文档") .contact(new Contact("rongrong", "", "emai@qq.com")) .description("这是SWAGGER_2生成的接口文档") .termsOfServiceUrl("NO terms of service") .license("The Apache License, Version 2.0") .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") .version("v1.0") .build(); } } |
重启服务:再次访问如下 from:https://www.cnblogs.com/longronglang/p/9045559.html
View Details综合概述 spring-boot作为当前最为流行的Java web开发脚手架,越来越多的开发者选择用其来构建企业级的RESTFul API接口。这些接口不但会服务于传统的web端(b/s),也会服务于移动端。在实际开发过程中,这些接口还要提供给开发测试进行相关的白盒测试,那么势必存在如何在多人协作中共享和及时更新API开发接口文档的问题。 假如你已经对传统的wiki文档共享方式所带来的弊端深恶痛绝,那么尝试一下Swagger2 方式,一定会让你有不一样的开发体验。 使用 Swagger 集成文档具有以下几个优势: 功能丰富 :支持多种注解,自动生成接口文档界面,支持在界面测试API接口功能; 及时更新 :开发过程中花一点写注释的时间,就可以及时的更新API文档,省心省力; 整合简单 :通过添加pom依赖和简单配置,内嵌于应用中就可同时发布API接口文档界面,不需要部署独立服务。 实现案例 接下来,我们就通过Spring Boot 来整合Swagger实现在线API文档的功能。 生成项目模板 为方便我们初始化项目,Spring Boot给我们提供一个项目模板生成网站。 1. 打开浏览器,访问:https://start.spring.io/ 2. 根据页面提示,选择构建工具,开发语言,项目信息等。 3. 点击 Generate the project,生成项目模板,生成之后会将压缩包下载到本地。 4. 使用IDE导入项目,我这里使用Eclipse,通过导入Maven项目的方式导入。 添加相关依赖 添加 Maven 相关依赖,这里需要添加上WEB和SWAGGER依赖。 WEB依赖
1 2 3 4 |
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> |
swagger依赖,这里选择 2.9.2 版本。
1 2 3 4 5 6 7 8 9 10 11 |
<!-- swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> |
添加配置类 添加一个swagger 配置类,在工程下新建 config 包并添加一个 SwaggerConfig 配置类。 SwaggerConfig.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()).build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("Kitty API Doc") .description("This is a restful api document of Kitty.") .version("1.0") .build(); } } |
添加控制器 添加一个控制器,在工程下新建 controller包并添加一个 HelloController控制器。 HelloController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.louis.springboot.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; /* 类注解 */ @Api(value = "desc of class") @RestController public class HelloController { /* 方法注解 */ @ApiOperation(value = "desc of method", notes = "") @GetMapping(value="/hello") public Object hello( /* 参数注解 */ @ApiParam(value = "desc of param" , required=true ) @RequestParam String name) { return "Hello " + name + "!"; } } |
编译运行测试 1. 右键项目 -> Run as -> Maven install,开始执行Maven构建,第一次会下载Maven依赖,可能需要点时间,如果出现如下信息,就说明项目编译打包成功了。 2. 右键文件 DemoApplication.java -> Run as -> Java Application,开始启动应用,当出现如下信息的时候,就说明应用启动成功了,默认启动端口是8080。 3. 打开浏览器,访问:http://localhost:8080/swagger-ui.html,进入swagger接口文档界面。 4. 展开hello-controller的hello接口,输入参数并点击执行,就可以看到接口测试结果了。 常用注解说明 swagger 通过注解接口生成文档,包括接口名,请求方法,参数,返回信息等。 @Api: 修饰整个类,用于controller类上 @ApiOperation: 描述一个接口,用户controller方法上 @ApiParam: 单个参数描述 @ApiModel: […]
View Details综合概述 Spring Security 是 Spring 社区的一个顶级项目,也是 Spring Boot 官方推荐使用的安全框架。除了常规的认证(Authentication)和授权(Authorization)之外,Spring Security还提供了诸如ACLs,LDAP,JAAS,CAS等高级特性以满足复杂场景下的安全需求。另外,就目前而言,Spring Security和Shiro也是当前广大应用使用比较广泛的两个安全框架。 Spring Security 应用级别的安全主要包含两个主要部分,即登录认证(Authentication)和访问授权(Authorization),首先用户登录的时候传入登录信息,登录验证器完成登录认证并将登录认证好的信息存储到请求上下文,然后再进行其他操作,如在进行接口访问、方法调用时,权限认证器从上下文中获取登录认证信息,然后根据认证信息获取权限信息,通过权限信息和特定的授权策略决定是否授权。 本教程将首先给出一个完整的案例实现,然后再分别对登录认证和访问授权的执行流程进行剖析,希望大家可以通过实现案例和流程分析,充分理解Spring Security的登录认证和访问授权的执行原理,并且能够在理解原理的基础上熟练自主的使用Spring Security实现相关的需求。 实现案例 接下来,我们就通过一个具体的案例,来讲解如何进行Spring Security的整合,然后借助Spring Security实现登录认证和访问控制。 生成项目模板 为方便我们初始化项目,Spring Boot给我们提供一个项目模板生成网站。 1. 打开浏览器,访问:https://start.spring.io/ 2. 根据页面提示,选择构建工具,开发语言,项目信息等。 3. 点击 Generate the project,生成项目模板,生成之后会将压缩包下载到本地。 4. 使用IDE导入项目,我这里使用Eclipse,通过导入Maven项目的方式导入。 添加相关依赖 清理掉不需要的测试类及测试依赖,添加 Maven 相关依赖,这里需要添加上web、swagger、spring security、jwt和fastjson的依赖,Swagge和fastjson的添加是为了方便接口测试。 pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.louis.springboot</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!-- web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <!-- spring security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- jwt --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <!-- fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.58</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <!-- 打包时拷贝MyBatis的映射文件 --> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/sqlmap/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> <filtering>true</filtering> </resource> </resources> </build> </project> |
添加相关配置 1.添加swagger 配置 添加一个swagger 配置类,在工程下新建 config 包并添加一个 SwaggerConfig 配置类,除了常规配置外,加了一个令牌属性,可以在接口调用的时候传递令牌。 SwaggerConfig.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package com.louis.springboot.demo.config; import java.util.ArrayList; import java.util.List; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.ParameterBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.schema.ModelRef; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Parameter; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi(){ // 添加请求参数,我们这里把token作为请求头部参数传入后端 ParameterBuilder parameterBuilder = new ParameterBuilder(); List<Parameter> parameters = new ArrayList<Parameter>(); parameterBuilder.name("Authorization").description("令牌").modelRef(new ModelRef("string")).parameterType("header") .required(false).build(); parameters.add(parameterBuilder.build()); return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()).build().globalOperationParameters(parameters); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("SpringBoot API Doc") .description("This is a restful api document of Spring Boot.") .version("1.0") .build(); } } |
加了令牌属性后的 Swagger 接口调用界面,会多出一个令牌参数,在发起请求的时候一起发送令牌。 2.添加跨域 配置 添加一个CORS跨域配置类,在工程下新建 config 包并添加一个 CorsConfig配置类。 CorsConfig.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.louis.springboot.demo.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 允许跨域访问的路径 .allowedOrigins("*") // 允许跨域访问的源 .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") // 允许请求方法 .maxAge(168000) // 预检间隔时间 .allowedHeaders("*") // 允许头部设置 .allowCredentials(true); // 是否发送cookie } } |
安全配置类 下面这个配置类是Spring Security的关键配置。 在这个配置类中,我们主要做了以下几个配置: 1. 访问路径URL的授权策略,如登录、Swagger访问免登录认证等 2. 指定了登录认证流程过滤器 JwtLoginFilter,由它来触发登录认证 3. 指定了自定义身份认证组件 JwtAuthenticationProvider,并注入 UserDetailsService 4. 指定了访问控制过滤器 JwtAuthenticationFilter,在授权时解析令牌和设置登录状态 5. 指定了退出登录处理器,因为是前后端分离,防止内置的登录处理器在后台进行跳转 WebSecurityConfig.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
package com.louis.springboot.demo.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; 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.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler; import com.louis.springboot.demo.security.JwtAuthenticationFilter; import com.louis.springboot.demo.security.JwtAuthenticationProvider; import com.louis.springboot.demo.security.JwtLoginFilter; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { // 使用自定义登录身份认证组件 auth.authenticationProvider(new JwtAuthenticationProvider(userDetailsService)); } @Override protected void configure(HttpSecurity http) throws Exception { // 禁用 csrf, 由于使用的是JWT,我们这里不需要csrf http.cors().and().csrf().disable() .authorizeRequests() // 跨域预检请求 .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 登录URL .antMatchers("/login").permitAll() // swagger .antMatchers("/swagger**/**").permitAll() .antMatchers("/webjars/**").permitAll() .antMatchers("/v2/**").permitAll() // 其他所有请求需要身份认证 .anyRequest().authenticated(); // 退出登录处理器 http.logout().logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()); // 开启登录认证流程过滤器 http.addFilterBefore(new JwtLoginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class); // 访问控制时登录状态检查过滤器 http.addFilterBefore(new JwtAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class); } @Bean @Override public AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } } |
登录认证触发过滤器 JwtLoginFilter 是在通过访问 /login 的POST请求是被首先被触发的过滤器,默认实现是 UsernamePasswordAuthenticationFilter,它继承了 AbstractAuthenticationProcessingFilter,抽象父类的 doFilter 定义了登录认证的大致操作流程,这里我们的 JwtLoginFilter 继承了 UsernamePasswordAuthenticationFilter,并进行了两个主要内容的定制。 1. […]
View Details