html登录页面代码_Spring Security接管Swagger认证授权,我发现仅用了3行关键代码!

接上篇《Apache Shiro 接管Swagger认证授权》,有热心网友反应Apache Shiro似乎太简单。针对这个问题,个人不做任何评价(一切技术服务于需求)。今天主要分享内容为:在Spring Security下如何接管Swagger的认证授权工作。

b1651343cc55238c651ae2ebd5d8cc48.png

1.添加依赖

假定你对Swagger和Spring Security已经有一定的基础,现在开始检查你的项目中是否添加了Swagger和Spring Security的依赖。以Maven为例,向pom.xml文件添加如下配置信息:

org.springframework.boot    spring-boot-starter-securityio.springfox    springfox-swagger2    2.9.2io.springfox    springfox-swagger-ui    2.9.2

2.配置Swagger

Swagger的配置相对比较简单,最主要的是配置其扫描的包路径,其他信息可以选配。你可以按照下列方式进行配置:

@Configuration@EnableSwagger2public class SwaggerConfiguration {    @Bean    public Docket docket(){        return new Docket(DocumentationType.SWAGGER_2)                .pathMapping("/")                .select()                .apis(            RequestHandlerSelectors.basePackage("com.ramostear.apisecurity.controller"))                .paths(PathSelectors.any())                .build()                .apiInfo(                    new ApiInfoBuilder()                    .title("Spring Security接管Swagger认证授权")                    .description("Spring Security and Swagger")                    .version("1.0.0")                    .contact(                        new Contact(                            "树下魅狐",                            "https://www.ramostear.com",                            "ramostear@163.com"                        )                    ).build()                );    }}

Swagger的配置基本与上一篇的内容一致,只是调整了basePackage的路径。

3.配置Spring Security

Spring Security的配置是本篇的重点。首先,基于内存设置两个登录时使用的账号,然后再将Swagger的资源路径添加到Spring Security的Authorize Filters中。创建Spring Security配置类,并添加如下代码(如果你已经配置过Spring Security,且基于JDBC获得登录账号信息,那么可以省略账户的配置)。

SpringSecurityConfiguration.java

@Configuration@EnableWebSecuritypublic class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {    private static final String[] AUTH_LIST = {      "/v2/api-docs",      "/configuration/ui",      "/swagger-resources/**",      "/configuration/security",      "/swagger-ui.html",      "/webjars/**"    };    @Override    protected void configure(AuthenticationManagerBuilder auth) throws Exception {        auth.inMemoryAuthentication()            .passwordEncoder(passwordEncoder())            .withUser("user")            .password(passwordEncoder().encode("password"))            .roles("USER");    }    @Override    protected void configure(HttpSecurity http) throws Exception {        http.authorizeRequests()            .antMatchers(AUTH_LIST)            .authenticated()            .and()            .formLogin()            .and()            .httpBasic();    }    @Bean    public PasswordEncoder passwordEncoder(){        return new BCryptPasswordEncoder();    }}

在配置类中,AUTH_LIST数组存放了Swagger需要加入Spring Security认证的URL:

private static final String[] AUTH_LIST = {      "/v2/api-docs",      "/swagger-resources/**",      "/swagger-ui.html",      "/webjars/**"    };

这和Apache Shiro中的配置如出一辙,下面是Apache Shiro中配置Swagger的代码:

@Beanpublic ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){    ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();    Map filterChainDefinition = new LinkedHashMap<>();    filterChainDefinition.put("/swagger-ui.html","authc");    filterChainDefinition.put("/v2/**","authc");    filterChainDefinition.put("/swagger-resources/**","authc");    filterFactoryBean.setFilterChainDefinitionMap(filterChainDefinition);    return filterFactoryBean;}

让Spring Security接管Swagger认证授权的核心是configure(HttpSecurity http)方法:

@Overrideprotected void configure(HttpSecurity http) throws Exception {    http.authorizeRequests()        .antMatchers(AUTH_LIST)        .authenticated()        .and()        .httpBasic();}

只需将Swagger的相关URLs加入到Spring Security认证过滤链中即可。当未经认证的用户访问Swagger文档时(http://localhost:8080/swagger-ui.html),页面将跳转到用户登录页面。

4.测试

现在,启动应用程序,并在浏览器地址栏输入:http://localhost:8080/swagger-ui.html 。按下回车键后,页面被跳转到登录页面。

79f13a0a367dfd254c3b25a4caed8660.png

接下来,使用之前配置的账号和密码登录(用户名:user,密码:password)。成功登录后,便可浏览Swagger文档页面信息。

3307505be448645634d17237505564f4.png

通过下面的动态图片,你可以更直观的了解测试过程:

c9d460f5db074f61f28ba60e5f261e92.gif

5.总结

本文详细介绍了在Spring Boot下,如果使用Spring Security接管Swagger默认的身份认证工作。通过与Apache Shiro管理Swagger认证授权会发现,Spring Security和Apache Shiro管理Swagger权限的逻辑基本一致,即将Swagger的URLs加入到各自的认证和授权过滤链中,当用户访问Swagger对应的资源时,Apache Shiro和Spring Security都会对当前请求路径进行检查(包括用户是否登录,当前用户是否有权限访问url)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security整合Swagger的过程中,我们需要进以下几个步骤: 1. 配置Spring Security:在Spring Security配置类中,我们可以使用`WebSecurityConfigurerAdapter`来配置权限过滤和访问控制。可以在`configure(HttpSecurity http)`方法中添加`.antMatchers("/swagger-ui.html").permitAll()`来允许Swagger UI页面的访问。这样,Swagger UI页面将不会被Spring Security拦截。 2. 配置静态资源:Swagger UI页面需要访问一些静态资源,例如Swagger API文档和UI配置文件。我们可以在Spring Security配置类中使用`WebSecurity.configure(WebSecurity web)`方法来配置这些静态资源的访问权限。可以使用`web.ignoring().antMatchers("/v2/api-docs", "/swagger-resources/configuration/ui", "/swagger-resources", "/swagger-resources/configuration/security", "/swagger-ui.html")`来允许这些静态资源的访问。 3. 添加相关依赖:在项目的pom.xml文件中,我们需要添加Spring SecuritySwagger的相关依赖。可以添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <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 SecuritySwagger的整合。 综上所述,以上是实现Spring Security整合Swagger的方法。通过配置Spring Security和静态资源,以及添加相关依赖,我们可以实现在Spring Boot项目中使用Spring Security保护接口并允许Swagger UI的访问[1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值