Spring Security起步零配置(一)

添加依赖

springboot的版本是 2.5.4,spring-security的版本是 5.5.2
build.gradle

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.5.4'
}

apply plugin: 'java'
apply plugin: 'io.spring.dependency-management'

group 'com.rick.security'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    implementation "org.springframework.boot:spring-boot-starter-security"
    implementation 'org.springframework.boot:spring-boot-starter-web'
}

test {
    useJUnitPlatform()
}

添加接口

IndexController.java

@RestController
public class IndexController {

    @GetMapping("index")
    public String index() {
        return "index";
    }
}

启动服务

启动服务后控制台生成密码,并打印过滤器信息

Using generated security password: bc180105-93f7-4bb4-9b35-63ac46f54cdd

2021-10-09 11:50:53.874  INFO 32471 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@1948ea69, org.springframework.security.web.context.SecurityContextPersistenceFilter@56303475, org.springframework.security.web.header.HeaderWriterFilter@706cb08, org.springframework.security.web.csrf.CsrfFilter@69c93ca4, org.springframework.security.web.authentication.logout.LogoutFilter@5f13be1, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@99a78d7, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@62e6a3ec, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@47e4d9d0, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@2d746ce4, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@1dcca8d3, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@4632cfc, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@49798e84, org.springframework.security.web.session.SessionManagementFilter@6b68cb27, org.springframework.security.web.access.ExceptionTranslationFilter@10876a6, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@e4d2696]

访问接口:

GET http://localhost:8080/index

默认所有的资源都是受保护的,会跳转到登录页面http://localhost:8080/login。 用户密码默认是 user,密码是控制台生成的。
login (1).png
登录之后,自动跳转到index。


关于作者

Rick
获得点赞
文章被阅读