当前位置: 代码迷 >> 综合 >> 二、SpringSecurity+auth2.0系列(form 表单模式)
  详细解决方案

二、SpringSecurity+auth2.0系列(form 表单模式)

热度:59   发布时间:2023-12-11 16:11:04.0

此模块基于模块一,读者可阅读本专栏

Form 表单模式 适合于传统模式项目 前端和后端都是我们java开发
修改配置完整代码如下

package com.thunisoft.spring_security.config;import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
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.NoOpPasswordEncoder;
import org.springframework.stereotype.Component;@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {/*** 新增 HttpSecurity基础配置配置*/// http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();/*** 新增HttpSecurity formLogin模式*///http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().formLogin();http.authorizeRequests().antMatchers("/addMember").hasAnyAuthority("addMember").antMatchers("/delMember").hasAnyAuthority("delMember").antMatchers("/showMember").hasAnyAuthority("showMember").antMatchers("/editMember").hasAnyAuthority("editMember").// antMatchers("/**").fullyAuthenticated().and().formLogin()antMatchers("/login").permitAll().antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").and().csrf().disable();}/** 新增授权账户* */@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//新增一个用户为orange和admin用户,权限不一样auth.inMemoryAuthentication().withUser("admin").password("admin").authorities("addMember","delMember","editMember","showMember");auth.inMemoryAuthentication().withUser("orange").password("orange").authorities("showMember");}/*** 密码不做任何处理* @return*/@Beanpublic static NoOpPasswordEncoder passwordEncoder(){return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();}}

配置权限策略
在企业管理系统平台中,会拆分成n多个不同的账号,
每个账号对应不同的接口访问权限,
比如
账号admin所有接口都可以访问;
orange账户 只能访问/addMember接口;
代码如上代码中所示

如何修改403权限不足页面
在config包下新建配置类,代码如下

package com.thunisoft.spring_security.config;import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;@Configuration
public class WebServerAutoConfiguration {/*** 授权失败调转页面* @return*/@Beanpublic ConfigurableServletWebServerFactory webServerFactory() {TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400");ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401");ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error/403");ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "/error/415");ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");factory.addErrorPages(errorPage400, errorPage401, errorPage403, errorPage404, errorPage415, errorPage500);return factory;}
}

在controller包下新建errorcontroller类
代码如下:

package com.thunisoft.spring_security.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class ErrorController {@RequestMapping("/error/403")public String error403() {return "您当前访问的接口权限不足!";}@RequestMapping("/error/400")public String error400() {return "您当前请求异常!";}@RequestMapping("/error/401")public String error401() {return "您的状态未认证!";}@RequestMapping("/error/404")public String error404() {return "页面未查询到!";}@RequestMapping("/error/415")public String error415() {return "请求格式错误!";}@RequestMapping("/error/500")public String error500() {return "服务器内部错误!";}}

登陆页面
包controller新建登录类
代码如下

package com.thunisoft.spring_security.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;@Controller
public class LoginController {@RequestMapping("/login")public String login() {return "login";}
}

导入freemarker依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

自定义登录页面login.ftl
在resource下新建templates,新建这个文件

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"><title>Insert title here</title>
</head>
<body><h1>权限控制登陆系统</h1>
<form action="/login" method="post"><span>用户名称</span><input type="text" name="username"/> <br><span>用户密码</span><input type="password" name="password"/> <br><input type="submit" value="登陆"></form><#if RequestParameters['error']??>
用户名称或者密码错误
</#if>
</body>
</html>

配置application.yml
次数为配置页面的参数

spring:freemarker:settings:classic_compatible: truedatetime_format: yyy-MM-dd HH:mmnumber_format: 0.##suffix: .ftltemplate-loader-path: classpath:/templates

运行项目,进行登录测试

  相关解决方案