1.首先需要添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.创建一个自己的安全类继承WebSecurityConfigurerAdapter,代码如下所示
,antMatchers("/").permitAll()表示根路径不需要任何权限,.antMatchers("/success").hasRole("vip1")需要VIP1的这种权限.withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")表示该用户登录具有的权限为VIP1,.formLogin()表示当你进入某个你没有权限的页面的时候跳转到登录页面,springsecurity自带了登录页面和登录功能,所以需要自定义登录页面采用.loginPage("/index.html"),自定义登录接口采用.loginProcessingUrl("/login"),
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/success").hasRole("vip1");
http.formLogin().loginPage("/index.html").loginProcessingUrl("/login").successForwardUrl("/success");
}
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2");
}
}
3.编写自己的登录页面,这里只需要自己稍加修改一下,
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:action="@{/login}" method="post">
<h1 th:text="#{username}"></h1>
<input type="text" name="username" th:placeholder="#{username}" value="admin"/>
<input type="text" name="password" th:placeholder="#{password}" value="123456"/>
<button>[[#{submit}]]</button>
<br>
<a th:href="@{/index.html(l='zh_CN')}">中文</a>
<br>
<a th:href="@{/index.html(l='en_US')}">english</a>
</form>
</body>
</html>
4.编写自己的登录接口和登录成功的接口
@RequestMapping("/login")
public String login(String username,String password){
return "redirect:success";
}
@RequestMapping("/success")
public String success(){
return "success";
}
5.说一下我遇到的问题
如果自定义登录页面一定需要设置name="username" 和name ="password",我由于忘记添加,让我找了几个小时,
网友评论