Skip to content

Commit ac579d4

Browse files
committed
spring security
1 parent 6203cd6 commit ac579d4

16 files changed

Lines changed: 659 additions & 24 deletions

security/pom.xml

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,27 @@
2525
<artifactId>spring-boot-starter-security</artifactId>
2626
</dependency>
2727

28+
<dependency>
29+
<groupId>mysql</groupId>
30+
<artifactId>mysql-connector-java</artifactId>
31+
</dependency>
32+
33+
<dependency>
34+
<groupId>org.springframework.boot</groupId>
35+
<artifactId>spring-boot-starter-data-jpa</artifactId>
36+
</dependency>
37+
38+
<dependency>
39+
<groupId>org.projectlombok</groupId>
40+
<artifactId>lombok</artifactId>
41+
<optional>true</optional>
42+
</dependency>
43+
44+
<dependency>
45+
<groupId>cn.hutool</groupId>
46+
<artifactId>hutool-all</artifactId>
47+
</dependency>
48+
2849
<dependency>
2950
<groupId>org.springframework.boot</groupId>
3051
<artifactId>spring-boot-starter-test</artifactId>
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
package org.ylc.note.security.common;
2+
3+
import org.ylc.note.security.constant.ConfigConstants;
4+
5+
import java.io.Serializable;
6+
7+
/**
8+
* 代码千万行,注释第一行,
9+
* 注释不规范,同事泪两行。
10+
*
11+
* 统一返回
12+
*
13+
* @author YuLc
14+
* @version 1.0.0
15+
* @date 2020/5/19
16+
*/
17+
public class HttpResult<T> implements Serializable {
18+
19+
20+
private static final long serialVersionUID = 1L;
21+
22+
private int code;
23+
24+
private String msg;
25+
26+
private T data;
27+
28+
public HttpResult(int code, String msg, T data) {
29+
this.code = code;
30+
this.msg = msg;
31+
this.data = data;
32+
}
33+
34+
public HttpResult() {
35+
this.code = ConfigConstants.Return.SUCCESS;
36+
this.msg = "SUCCESS";
37+
}
38+
39+
public HttpResult(T data) {
40+
this();
41+
this.data = data;
42+
}
43+
44+
/**
45+
* 成功返回
46+
*
47+
* @param msg 成功信息
48+
* @param body 返回数据
49+
* @return Result
50+
*/
51+
public static <T> HttpResult<T> success(String msg, T body) {
52+
return new HttpResult<>(ConfigConstants.Return.SUCCESS, msg, body);
53+
}
54+
55+
/**
56+
* 成功返回
57+
*
58+
* @param body 返回数据
59+
* @return Result
60+
*/
61+
public static <T> HttpResult<T> success(T body) {
62+
return success("success", body);
63+
}
64+
65+
/**
66+
* 成功返回
67+
*
68+
* @return Result
69+
*/
70+
public static <T> HttpResult<T> success() {
71+
return success(null);
72+
}
73+
74+
/**
75+
* 失败返回
76+
*
77+
* @param code 错误编码
78+
* @param msg 错误信息
79+
* @return Result
80+
*/
81+
public static <T> HttpResult<T> fail(int code, String msg) {
82+
return new HttpResult<>(code, msg, null);
83+
}
84+
85+
/**
86+
* 普通失败返回
87+
*
88+
* @param msg 错误信息
89+
* @return Result
90+
*/
91+
public static <T> HttpResult<T> fail(String msg) {
92+
return fail(ConfigConstants.Return.OPERATION_FAILED, msg);
93+
}
94+
95+
public int getCode() {
96+
return code;
97+
}
98+
99+
public String getMsg() {
100+
return msg;
101+
}
102+
103+
public T getData() {
104+
return data;
105+
}
106+
107+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package org.ylc.note.security.config;
2+
3+
import org.springframework.security.access.AccessDecisionManager;
4+
import org.springframework.security.access.AccessDeniedException;
5+
import org.springframework.security.access.ConfigAttribute;
6+
import org.springframework.security.authentication.AnonymousAuthenticationToken;
7+
import org.springframework.security.authentication.BadCredentialsException;
8+
import org.springframework.security.authentication.InsufficientAuthenticationException;
9+
import org.springframework.security.core.Authentication;
10+
import org.springframework.security.core.GrantedAuthority;
11+
import org.springframework.stereotype.Component;
12+
13+
import java.util.Collection;
14+
15+
/**
16+
* 代码千万行,注释第一行,
17+
* 注释不规范,同事泪两行。
18+
* <p>
19+
* 访问控制
20+
*
21+
* @author YuLc
22+
* @version 1.0.0
23+
* @date 2020/5/19
24+
*/
25+
@Component
26+
public class CustomAccessDecisionManager implements AccessDecisionManager {
27+
28+
@Override
29+
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
30+
for (ConfigAttribute ca : configAttributes) {
31+
//当前请求需要的权限
32+
String needRole = ca.getAttribute();
33+
if ("ROLE_LOGIN".equals(needRole)) {
34+
if (authentication instanceof AnonymousAuthenticationToken) {
35+
throw new BadCredentialsException("未登录");
36+
} else
37+
return;
38+
}
39+
//当前用户所具有的权限
40+
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
41+
for (GrantedAuthority authority : authorities) {
42+
if (authority.getAuthority().equals(needRole)) {
43+
return;
44+
}
45+
}
46+
}
47+
throw new AccessDeniedException("权限不足!");
48+
}
49+
50+
@Override
51+
public boolean supports(ConfigAttribute attribute) {
52+
return true;
53+
}
54+
55+
@Override
56+
public boolean supports(Class<?> clazz) {
57+
return true;
58+
}
59+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package org.ylc.note.security.config;
2+
3+
import org.springframework.security.authentication.AuthenticationServiceException;
4+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
5+
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
6+
import org.springframework.security.core.AuthenticationException;
7+
import org.springframework.security.core.userdetails.UserDetails;
8+
import org.springframework.web.context.request.RequestContextHolder;
9+
import org.springframework.web.context.request.ServletRequestAttributes;
10+
11+
import javax.servlet.http.HttpServletRequest;
12+
13+
/**
14+
* 代码千万行,注释第一行,
15+
* 注释不规范,同事泪两行。
16+
* <p>
17+
* 自定义登录验证
18+
*
19+
* @author YuLc
20+
* @version 1.0.0
21+
* @date 2020/5/13
22+
*/
23+
public class MyAuthenticationProvider extends DaoAuthenticationProvider {
24+
25+
@Override
26+
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
27+
// 获取请求信息
28+
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
29+
// 获取验证码信息
30+
String code = request.getParameter("code");
31+
// 从session中获取验证码字符串
32+
String verifyCode = (String) request.getSession().getAttribute("verify_code");
33+
// 校验验证码
34+
if (code == null || verifyCode == null || !code.equals(verifyCode)) {
35+
throw new AuthenticationServiceException("验证码错误");
36+
}
37+
super.additionalAuthenticationChecks(userDetails, authentication);
38+
}
39+
}
Lines changed: 65 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,22 @@
11
package org.ylc.note.security.config;
22

3+
import lombok.extern.slf4j.Slf4j;
34
import org.springframework.context.annotation.Bean;
45
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
7+
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
8+
import org.springframework.security.authentication.AuthenticationManager;
9+
import org.springframework.security.authentication.ProviderManager;
510
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
611
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
712
import org.springframework.security.config.annotation.web.builders.WebSecurity;
813
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
914
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
1015
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
1116
import org.springframework.security.crypto.password.PasswordEncoder;
17+
import org.ylc.note.security.service.UserService;
18+
19+
import java.util.Collections;
1220

1321
/**
1422
* 代码全万行,注释第一行
@@ -20,38 +28,85 @@
2028
* @version 1.0.0
2129
* @date 2020-05-18
2230
*/
31+
@Slf4j
2332
@Configuration
2433
@EnableWebSecurity
2534
public class SecurityConfig extends WebSecurityConfigurerAdapter {
2635

36+
private final UserService userService;
37+
38+
public SecurityConfig(UserService userService) {
39+
this.userService = userService;
40+
}
41+
42+
/**
43+
* 配置密码解密
44+
*/
2745
@Bean
2846
PasswordEncoder passwordEncoder() {
47+
log.info("配置密码不加密");
2948
return NoOpPasswordEncoder.getInstance();
3049
}
3150

51+
/**
52+
* 配置角色继承
53+
* 表示 ROLE_admin 自动具备 ROLE_user 的权限
54+
*/
55+
@Bean
56+
RoleHierarchy roleHierarchy() {
57+
log.info("配置角色继承关系");
58+
RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
59+
hierarchy.setHierarchy("ROLE_admin > ROLE_user");
60+
return hierarchy;
61+
}
62+
63+
/**
64+
* 注入自定义的验证逻辑
65+
*/
66+
@Bean
67+
MyAuthenticationProvider myAuthenticationProvider() {
68+
MyAuthenticationProvider myAuthenticationProvider = new MyAuthenticationProvider();
69+
myAuthenticationProvider.setPasswordEncoder(passwordEncoder());
70+
myAuthenticationProvider.setUserDetailsService(userDetailsService());
71+
return myAuthenticationProvider;
72+
}
73+
3274
@Override
33-
public void configure(WebSecurity web) throws Exception {
34-
web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");
75+
protected AuthenticationManager authenticationManager() throws Exception {
76+
return new ProviderManager(Collections.singletonList(myAuthenticationProvider()));
3577
}
3678

79+
/**
80+
* 用户相关
81+
*/
3782
@Override
3883
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
39-
auth.inMemoryAuthentication()
40-
.withUser("ylc")
41-
.password("9527")
42-
.roles("admin");
84+
log.info("配置用户相关验证");
85+
auth.userDetailsService(userService);
86+
}
87+
88+
@Override
89+
public void configure(WebSecurity web) {
90+
log.info("配置忽略校验路径");
91+
web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");
4392
}
4493

4594
@Override
4695
protected void configure(HttpSecurity http) throws Exception {
96+
log.info("配置http规则");
4797
http.authorizeRequests()
98+
.antMatchers("/admin/**").hasRole("admin")
99+
.antMatchers("/user/**").hasRole("user")
48100
.anyRequest().authenticated()
49101
.and()
50-
.formLogin()
51-
//.loginPage("/login.html")
52-
.permitAll()
102+
.formLogin().permitAll()
103+
.and()
104+
.rememberMe()
105+
// 自己设置密令后,即使服务器重启也能实现自动登录,该值默认为一个UUID字符串
106+
.key("9527")
53107
.and()
54-
.csrf().disable();
108+
.csrf().disable()
109+
;
55110
}
56111

57112
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package org.ylc.note.security.constant;
2+
3+
/**
4+
* 系统配置常量
5+
*
6+
* @author YuLc
7+
* @version 1.0.0
8+
* @date 2020/5/19
9+
*/
10+
public class ConfigConstants {
11+
12+
/**
13+
* 请求返回
14+
*/
15+
public static class Return {
16+
/**
17+
* 成功
18+
*/
19+
public static final int SUCCESS = 200;
20+
/**
21+
* 操作失败,统一返回代码编号,直接打印出msg信息
22+
*/
23+
public static final int OPERATION_FAILED = 500;
24+
/**
25+
* 没有访问权限,提示非法操作
26+
*/
27+
public static final int ACCESS_RESTRICTED = 403;
28+
/**
29+
* token过期,引导到登录界面
30+
*/
31+
public static final int TOKEN_EXPIRED = 401;
32+
}
33+
34+
}

0 commit comments

Comments
 (0)