版权声明:版权声明:本文为博主原创文章,欢迎转载,转载请注明作者、原文超链接 https://blog.csdn.net/qq_35098526/article/details/87931863
springboot整合Spring Security
简介
-
Spring Security是一个功能强大且可高度自定义的身份验证和访问控制框架。它是保护基于Spring的应用程序的事实标准。
-
Spring Security是一个专注于为Java应用程序提供身份验证和授权的框架。与所有Spring项目一样,Spring Security的真正强大之处在于它可以轻松扩展以满足自定义要求
准备工作
- pom.xml jar引入:
<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>
项目要点
1.application.yml配置
spring:
freemarker:
suffix: .html
request-context-attribute: request
2.创建SecurityConfig类
- 通过@EnableWebSecurity注解开启Spring Security的功能
- 继承WebSecurityConfigurerAdapter,并重写它的方法来设置一些web安全的细节
- configure(HttpSecurity http)方法
- 通过authorizeRequests()定义哪些URL需要被保护、哪些不需要被保护。
- 通过formLogin()定义当需要用户登录时候,转到的登录页面。
package com.honghh.bootfirst.config;
import com.honghh.bootfirst.service.CustomUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.password.PasswordEncoder;
import javax.annotation.Resource;
/**
* ClassName: SecurityConfig
* Description:
*
* @author honghh
* @date 2019/02/23 16:18
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
CustomUserService customUserService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
// 根据配置文件放行无需验证的url
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
/**
* 定义认证用户信息获取来源,密码校验规则等
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService)
.passwordEncoder(new PasswordEncoder() {
@Override
public String encode(CharSequence charSequence) {
System.out.println("encode"+charSequence.toString());
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
});
}
}
3.创建HelloWordController类
package com.honghh.bootfirst.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* ClassName: HelloWordController
* Description:
*
* @author honghh
* @date 2019/02/19 15:58
*/
@Controller
public class HelloWordController {
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("/main")
public String main() {
return "main";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "login";
}
}
4.创建一个CustomUserService类,对CustomUserServiceImpl实现
CustomUserService只定义了一个方法loadUserByUsername,根据用户名可以查到用户并返回的方法。
package com.honghh.bootfirst.service;
import org.springframework.security.core.userdetails.UserDetailsService;
/**
* ClassName: CustomUserService
* Description:
*
* @author honghh
* @date 2019/02/25 13:36
*/
public interface CustomUserService extends UserDetailsService {
}
# CustomUserServiceImpl 实现
package com.honghh.bootfirst.service.impl;
import com.honghh.bootfirst.service.CustomUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set;
/**
* ClassName: CustomUserServiceImpl
* Description:
*
* @author honghh
* @date 2019/02/25 13:38
*/
@Service
public class CustomUserServiceImpl implements CustomUserService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Set<GrantedAuthority> authorities = new HashSet<>();
if("admin".equalsIgnoreCase(username)) {
// 添加权限
authorities.add(new SimpleGrantedAuthority("test"));
authorities.add(new SimpleGrantedAuthority("admin"));
} else {
authorities.add(new SimpleGrantedAuthority("test"));
}
User user = new User(username, "123456", authorities);
return user;
}
}
5 成功页面
- 根据配置,Spring Security提供了一个过滤器来拦截请求并验证用户身份。如果用户身份认证失败,页面就重定向到/login?error,并且页面中会展现相应的错误信息。若用户想要注销登录,可以通过访问/login?logout请求,在完成注销之后,页面展现相应的成功消息。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
用户名或密码错
</div>
<div th:if="${param.logout}">
您已注销成功
</div>
<form th:action="@{/login}" method="post">
<div><label> 用户名 : <input type="text" name="username"/> </label></div>
<div><label> 密 码 : <input type="password" name="password"/> </label></div>
<div><input type="submit" value="登录"/></div>
</form>
</body>
</html>
代码获取
https://gitee.com/honghh/boot-demo.git
参考文献
-
Spring Security
https://spring.io/projects/spring-security -
Spring Boot中使用Spring Security进行安全控制
http://blog.didispace.com/springbootsecurity/ -
Spring Security Reference
https://docs.spring.io/spring-security/site/docs/5.1.4.RELEASE/reference/html5/