一 自定义认证页面
1.1 说明
1. 如果用户没有自定义登录页面,spring security 默认会启动自身内部的登录页面,尽管自动生成的登录页面很方便 快速启动和运行,但大多数应用程序都希望定义自己的登录页面。
1.2 自定义登录页面
在新建一个webapp目录,和resouces目录,平级,将login.jsp页面考配到这个页面下:
mylogin.jsp 页面代码:
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %>
<html>
<head>
<title>用户登录</title>
</head>
<body>
<form action="login" method="post">
用户名:<input type="text" name="username"><br>
密 码:
<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
1.2 配置视图
在application配置视图跳转的位置
1.3 认证页面的配置
在WebConfig.java中配置认证页面地址:
说明:这里的 setViewName("mylogin"); 指向的是webapp/WEB-INF/view下的mylogin.jsp页面
@Configuration//就相当于springmvc.xml文件
public class WebConfig implements WebMvcConfigurer {
//默认Url根路径跳转到/login,此url为spring security提供
@Override
public void addViewControllers(ViewControllerRegistry registry) {
System.out.println("webconfig类中的视图器....");
//这里的setViewName("redirect:/login")跳转spring security跳转自带的登录页面login.jsp页面
// registry.addViewController("/").setViewName("redirect:/login");
registry.addViewController("/").setViewName("redirect:/login-view");
registry.addViewController("/login-view").setViewName("mylogin");
}
}
1.4 配置安全登录信息
在WebSecurityConfig中配置表登录信息:
1.fromLogin(): 允许表单登录
2.loginPage(): 指定我们自己的登录页
3.loginProcessingUrl(): 指定处理登录的URL,也就是用户名、密码表单提交的目的路径
4.successForwardUrl():指定登录成功后的跳转URL
5.formLogin().permitAll() 我们必须允许所有用户访问我们的登录页(例如为验证的用户),这个 formLogin().permitAll() 方法允许 任意用户访问基于表单登录的所有的URL。
3.代码信息:
package com.ljf.spt.security.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
/**
* @author Administrator
* @version 1.0
**/
//@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//1.定义用户信息服务(查询用户信息)
@Bean
public UserDetailsService userDetailsService(){
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build());
manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build());
return manager;
}
//2.密码编码器
@Bean
public PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
//3.安全拦截机制(最重要)
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable(); //屏蔽CSRF控制,即spring security不再限制CSRF
http.authorizeRequests()
.antMatchers("/user/r1").hasAuthority("p1") //p1角色具有访问/user/r1读取权限
.antMatchers("/user/r2").hasAuthority("p2") //p2角色具有访问/user/r2读取权限
.antMatchers("/user/**").authenticated()//所有/user/**的请求必须认证通过
.anyRequest().permitAll()//除了/user/**,其它的请求可以不经过认证,就可以访问
.and()
.formLogin()//允许表单登录
.loginPage("/login-view")//指定我们自己的登录页
.loginProcessingUrl("/login") //设置登录页面,用户名和密码提交的表单请求页面
.successForwardUrl("/login-success") //自定义登录成功的页面地址,登录成功跳转的地址
// 我们必须允许所有用户访问我们的登录页(例如为验证的用户),这个 formLogin().permitAll() 方法允许 任意用户访问基于表单登录的所有的URL。
.permitAll();//
//
}
}
1.5 controller登录信息
1.截图
2. 代码:
package com.ljf.spt.ss.controller;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @ClassName: LoginController
* @Description: TODO
* @Author: admin
* @Date: 2023/08/03 18:59:45
* @Version: V1.0
**/
@RestController
public class LoginController {
@RequestMapping(value = "/login-success",produces = {"text/plain;charset=UTF-8"})
public String loginSuccess(){
return geteUsername()+" 登录成功";
}
/**
* 测试资源1
* @return
*/
@GetMapping(value = "/user/r1",produces = {"text/plain;charset=UTF-8"})
public String r1(){
return geteUsername()+" 访问资源1";
}
/**
* 测试资源2
* @return
*/
@GetMapping(value = "/user/r2",produces = {"text/plain;charset=UTF-8"})
public String r2(){
return geteUsername()+" 访问资源2";
}
//获取当前用户信息
private String geteUsername(){
String username = null;
//当前认证通过的用户身份
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//用户身份
Object principal = authentication.getPrincipal();
if(principal == null){
username = "匿名";
}
if(principal instanceof UserDetails){
UserDetails userDetails = (UserDetails) principal;
username = userDetails.getUsername();
}else{
username = principal.toString();
}
return username;
}
}
1.6 启动springboot项目
地址: http://localhost:8080/spt-security/login-view
访问资源r1
访问资源r2: