Spring-Security基本使用

概述

spring security基本项目搭建。

代码

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

application.yml

1
2
3
4
5
6
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
cache: false
mode: HTML

templates/login.html

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
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" class="uk-height-1-1">
<head>
<meta charset="UTF-8"/>
<title>OAuth2 SSO Demo</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/2.26.3/css/uikit.gradient.min.css"/>
</head>

<body class="uk-height-1-1">

<div class="uk-vertical-align uk-text-center uk-height-1-1">
<div class="uk-vertical-align-middle" style="width: 250px;">
<h1>Login Form</h1>

<p class="uk-text-danger" th:if="${param.error}">
Login failed ...
</p>

<p class="uk-text-success" th:if="${param.logout}">
Logout succeeded.
</p>

<form class="uk-panel uk-panel-box uk-form" method="post" th:action="@{/web/login}">
<div class="uk-form-row">
<input class="uk-width-1-1 uk-form-large" type="text" placeholder="Username" name="username"
value="user"/>
</div>
<div class="uk-form-row">
<input class="uk-width-1-1 uk-form-large" type="password" placeholder="Password" name="password"
value="123"/>
</div>
<div class="uk-form-row">
<button class="uk-width-1-1 uk-button uk-button-primary uk-button-large">Login</button>
</div>
</form>
</div>
</div>
</body>
</html>

Main

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
@SpringBootApplication
public class IdcSecurityApplication {

public static void main(String[] args) {
SpringApplication.run(IdcSecurityApplication.class, args);
}

@Configuration
@EnableWebSecurity
@Order(1)
static class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

auth
.inMemoryAuthentication()
.withUser("user").password(passwordEncoder.encode("123")).roles("USER").and()
.withUser("manager").password(passwordEncoder.encode("123")).roles("MANAGER");

}

@Override
protected void configure(HttpSecurity http) throws Exception {

http.antMatcher("/web/**") // the filter chain defined for web request
.authorizeRequests()
.antMatchers("/web/report/**").hasRole("MANAGER")
.anyRequest().authenticated()
.and()
.formLogin()
// login 的相对路径必须与 security chain 的的相对路径吻合,这里是 /web/**;注意 login 分两步,一步是 Getter 会到 login.html,另外一步是从 login.html -> post -> /web/login/
.loginPage("/web/login") // http://localhost:8080/web/login
// 允许访问
.permitAll();

}
}

@Configuration
@EnableWebSecurity
@Order(2)
static class RestSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {

http.antMatcher("/rest/**") // the filter chain defined for web request;
.csrf().disable() // rest 请求无需 CSRF Token;
.authorizeRequests()
.antMatchers("/rest/hello").hasRole("USER")
.anyRequest().authenticated()
.and()
.httpBasic();

}
}

@Bean
PasswordEncoder passwordEncoder(){
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

}

IndexContrller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Controller
public class IndexController {

@GetMapping("/web/login")
public ModelAndView login() {
return new ModelAndView("login");
}

@GetMapping
@ResponseBody
public Object index() {
return "hello";
}
}

源码

  • SecurityAutoConfiguration
  • SecurityFilterAutoConfiguration
  • DelegatingFilterProxy
  • EnableWebSecurity
  • WebSecurityConfiguration
  • WebSecurity
  • FilterChainProxy
  • SecurityFilterChain

最后

本文到此结束,感谢阅读。如果您觉得不错,请关注公众号【当我遇上你】,您的支持是我写作的最大动力。

参考