本案例源码获得地址
SpringBootSecurity
创建SpringBootSecurity
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>pers.xipiker</groupId>
<artifactId>springbootsecurity</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootsecurity</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
spring:
thymeleaf:
mode: HTML5
encoding: UTF-8
cache: false
MyPasswordEncoder.java
package pers.xipiker.springbootsecurity.config;
import org.springframework.security.crypto.password.PasswordEncoder;
public class MyPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
}
SecurityConfig.java
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
//auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("forezp").password("123456").roles("USER");
auth.userDetailsService(userDetailsService()).passwordEncoder(new MyPasswordEncoder());
}
public UserDetailsService userDetailsService(){
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//在内存中存放用户信息
manager.createUser(User.withUsername("forezp").password("123456").roles("USER").build());
manager.createUser(User.withUsername("admin").password("123456").roles("ADMIN","USER").build());
return manager;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/css/**", "/index").permitAll()
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/blogs/**").hasRole("USER")
.and()
.formLogin().loginPage("/login").failureUrl("/login-error")
.and()
.exceptionHandling().accessDeniedPage("/401");
http.logout().logoutSuccessUrl("/");
}
}
Blog.java
public class Blog {
private Long id;
private String name;
private String content;
public Blog(Long id, String name, String content) {
this.id = id;
this.name = name;
this.content = content;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
IBlogService.java
public interface IBlogService {
List<Blog> getBlogs();
void deleteBlog(Long id);
}
BlogService.java
@Service
public class BlogService implements IBlogService {
private List<Blog> list = new ArrayList<>();
public BlogService() {
list.add(new Blog(1L, "Spring in action", "good!"));
list.add(new Blog(2L, "Spring boot in action", "nice!"));
}
@Override
public List<Blog> getBlogs() {
return list;
}
@Override
public void deleteBlog(Long id) {
Iterator iterator = list.iterator();
while (iterator.hasNext()){
Blog blog = (Blog) iterator.next();
if(blog.getId() == id){
iterator.remove();
}
}
}
}
MainController.java
@Controller
public class MainController {
@RequestMapping("/")
public String root(){
return "redirect:/index";
}
@RequestMapping("/index")
public String index(){
return "index";
}
@RequestMapping("/user/index")
public String userIndex(){
return "user/index";
}
@RequestMapping("/login")
public String login(){
return "login";
}
@RequestMapping("/login-error")
public String loginError(Model model){
model.addAttribute("loginError", true);
return "login";
}
@GetMapping("/401")
public String accesssDenied(){
return "401";
}
}
BlogController.java
@Controller
public class BlogController {
@Autowired
BlogService blogService;
// @GetMapping("/user/emps")
// public String list(Model model){
// List<tUser> list = tUserService.getAll();
// log.info("list-----{}", list);
// model.addAttribute("listResult", list);
// return "emp/list";
// }
@GetMapping("/blogs")
public String list(Model model){
List<Blog> list = blogService.getBlogs();
model.addAttribute("listResult", list);
return "blogs/list";
//return new ModelAndView("blogs/list", "blogModel", model);
}
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
@GetMapping(value = "/blogs/{id}")
public String delete(@PathVariable("id") Long id, Model model){
blogService.deleteBlog(id);
model.addAttribute("listResult", blogService.getBlogs());
//return new ModelAndView("blogs/list", "blogModel", model);
return "blogs/list";
}
}