springboot-security模块搭建

springboot-security模块搭建,第1张

Spring Security简介

Spring Security致力于为Java应用提供认证和授权管理。是一个强大的,高度自定义的认证和访问控制框架。
具体详细介绍看官网介绍 官方文档地址

优点
Spring Boot 官方提供了大量的非常方便的开箱即用的 Starter ,包括 Spring Security 的 Starter ,使得在 Spring Boot 中使用 Spring Security 变得更加容易。

缺点
重量级的安全管理框架,
概念复杂,配置繁琐

案例
我们在访问一个网站时,大都都会设置普通用户能有的权限,然后管理员有的权限,再就是超级管理员等等,下边搭建一个这样的demo

准备数据库表

CREATE TABLE `account` (
     `id` int(10) NOT NULL AUTO_INCREMENT,
     `username` varchar(25) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
     `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
     `role` varchar(25) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
     PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
 
INSERT INTO `account` VALUES (1, 'user', 'aMHNdZS.oCICxLRVbnNBZe4CRn9Rk1MVQhasSMhHr0G4BCNQjPpna', 'ROLE_USER');
INSERT INTO `account` VALUES (2, 'admin', 'a$dKkrkgVzaCPX74TvxOjwNuFJjIRJeAuDPKFntwNwRvRHkwIAHV5Q6', 'ROLE_ADMIN');
INSERT INTO `account` VALUES (3, 'super_admin', 'a$CqOXnSp6oks9UTvsops4U.0vMGbUE2Bp28xKaPmlug4W8Mk59Sj8y', 'ROLE_SUPER_ADMIN');
INSERT INTO `account` VALUES (4, 'test', 'a$SQsuH1XfxHdsVmf2nE75wOAE6GHm1nd/xDp/08KYJmtbzJt2J6xIG', 'TEST');

导入依赖

		<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-securityartifactId>
            <version>2.6.7version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.4.1version>
        dependency>

        <dependency>
            <groupId>io.jsonwebtokengroupId>
            <artifactId>jjwtartifactId>
            <version>0.9.0version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

配置文件

server:
  port: 8080
logging:
  level:
    com:
      crush:
        security:
          mapper: DEBUG
mybatis-plus:
  mapper-locations: classpath:mapper/**/*.xml
spring:
  application:
    name: secutiry
  datasource:
    name: defaultDataSource
    password: 123456
    url: jdbc:mysql://localhost:3306/security?serverTimezone=UTC
    username: root
token:
  expire: 3600000
  key: 123456

WebSecurityConfig Security的主要配置类:

package com.example.springbootsecurity.config;

import com.example.springbootsecurity.filter.JwtAuthenticationFilter;
import com.example.springbootsecurity.filter.JwtAuthorizationFilter;
import com.example.springbootsecurity.service.impl.UserDetailsServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * springboot-study
 * 

SpringSecurity配置类

* * @author : ZhangYuJie * @date : 2022-05-15 16:23 **/
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @RequiredArgsConstructor public class WebSecurityConfig extends WebSecurityConfigurerAdapter { /** * 放行的路径 */ private final String[] PATH_RELEASE = { "/login", "/all" }; /***根据用户名找到用户*/ private final UserDetailsServiceImpl userDetailService; private final MacLoginUrlAuthenticationEntryPoint macLoginUrlAuthenticationEntryPoint; private final MyAccessDeniedHandler myAccessDeniedHandler; private final MyLogoutSuccessHandler myLogoutSuccessHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable(); http.authorizeRequests() /**antMatchers (这里的路径) permitAll 这里是允许所有人 访问*/ .antMatchers(PATH_RELEASE).permitAll() /** 映射任何请求 */ .anyRequest() /** 指定任何经过身份验证的用户都允许使用URL。*/ .authenticated() /** 指定支持基于表单的身份验证 */ .and().formLogin().permitAll() /** 允许配置异常处理。可以自己传值进去 使用WebSecurityConfigurerAdapter时,将自动应用此WebSecurityConfigurerAdapter 。*/ .and().exceptionHandling() /** 设置要使用的AuthenticationEntryPoint。 macLoginUrlAuthenticationEntryPoint 验证是否登录*/ .authenticationEntryPoint(macLoginUrlAuthenticationEntryPoint) /** 指定要使用的AccessDeniedHandler 处理拒绝访问失败。*/ .accessDeniedHandler(myAccessDeniedHandler) /** 提供注销支持。 使用WebSecurityConfigurerAdapter时,将自动应用此WebSecurityConfigurerAdapter 。 * 默认设置是访问URL “ / logout”将使HTTP会话无效,清理配置的所有rememberMe()身份验证,清除SecurityContextHolder , * 然后重定向到“ / login?success”,从而注销用户*/ .and().logout().logoutSuccessHandler(myLogoutSuccessHandler) /** 处理身份验证表单提交。 授予权限 */ .and().addFilter(new JwtAuthenticationFilter(authenticationManager())) /** 处理HTTP请求的BASIC授权标头,然后将结果放入SecurityContextHolder 。 */ .addFilter(new JwtAuthorizationFilter(authenticationManager())) /**不需要session */ .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } @Override public void configure(WebSecurity web) throws Exception { super.configure(web); } /** * 因为使用了BCryptPasswordEncoder来进行密码的加密,所以身份验证的时候也的用他来判断 * * @param auth * @throws Exception */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder()); } /** * 密码加密 */ @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }

Security身份验证

package com.example.springbootsecurity.filter;

import com.example.springbootsecurity.entity.MyUser;
import com.example.springbootsecurity.util.JwtTokenUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;

/**
 * springboot-study
 * 

处理身份验证

* * @author : ZhangYuJie * @date : 2022-05-15 16:49 **/
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private AuthenticationManager authenticationManager; public JwtAuthenticationFilter(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } /** * 执行实际的身份验证。 * 该实现应执行以下 *** 作之一: * 返回已验证用户的已填充验证令牌,指示验证成功 * 返回null,表示身份验证过程仍在进行中。 在返回之前,实现应执行完成该过程所需的任何其他工作。 * 如果身份验证过程失败,则抛出AuthenticationException */ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { //输入流中获取到登录的信息 try { MyUser loginUser = new ObjectMapper().readValue(request.getInputStream(), MyUser.class); logger.info("loginUser===>" + loginUser); /** * authenticate * 尝试对传递的Authentication对象进行身份Authentication , * 如果成功,则返回完全填充的Authentication对象(包括授予的权限) * */ return authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList<>()) ); } catch (IOException e) { e.printStackTrace(); return null; } } /** * 成功验证后调用的方法 * 如果验证成功,就生成token并返回 */ @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { // 查看源代码会发现调用getPrincipal()方法会返回一个实现了`UserDetails`接口的对象 // 所以就是JwtUser啦 MyUser user = (MyUser) authResult.getPrincipal(); String role = ""; // 因为在JwtUser中存了权限信息,可以直接获取,由于只有一个角色就这么干了 Collection<? extends GrantedAuthority> authorities = user.getAuthorities(); for (GrantedAuthority authority : authorities) { role = authority.getAuthority(); } // 根据用户名,角色创建token并返回json信息 String token = JwtTokenUtils.createToken(user.getUsername(), role, false); user.setPassword(null); user.setToken(JwtTokenUtils.TOKEN_PREFIX + token); response.setStatus(HttpServletResponse.SC_OK); response.setHeader("token", JwtTokenUtils.TOKEN_PREFIX + token); response.setContentType("application/json;charset=utf-8"); PrintWriter writer = response.getWriter(); writer.write(new ObjectMapper().writeValueAsString(user)); } /** * 验证失败时候调用的方法 */ @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.setContentType("application/json;charset=utf-8"); PrintWriter writer = response.getWriter(); writer.write(new ObjectMapper().writeValueAsString("登录失败,账号或密码错误")); } }

Security授权

package com.example.springbootsecurity.filter;

import com.example.springbootsecurity.util.JwtTokenUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * springboot-study
 * 

处理HTTP请求的BASIC授权标头,然后将结果放入SecurityContextHolder

* * @author : ZhangYuJie * @date : 2022-05-15 16:51 **/
public class JwtAuthorizationFilter extends BasicAuthenticationFilter { public JwtAuthorizationFilter(AuthenticationManager authenticationManager) { super(authenticationManager); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER); // 如果请求头中没有Authorization信息则直接放行了 if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)) { chain.doFilter(request, response); return; } // 如果请求头中有token,则进行解析,并且设置认证信息 SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader)); super.doFilterInternal(request, response, chain); } /** * 这里从token中获取用户信息并新建一个token */ private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) { String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, ""); String username = JwtTokenUtils.getUsername(token.trim()); String role = JwtTokenUtils.getUserRole(token); if (username != null) { return new UsernamePasswordAuthenticationToken(username, null, Collections.singleton(new SimpleGrantedAuthority(role)) ); } return null; } }

UserDetailsService
UserDetailServiceImpl 实现了UserDetailsService,用来加载用户特定数据的核心接口。

package com.example.springbootsecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springbootsecurity.entity.MyUser;
import com.example.springbootsecurity.service.IMyUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * springboot-study
 * 

* * @author : ZhangYuJie * @date : 2022-05-15 16:48 **/
@Slf4j @Service @RequiredArgsConstructor public class UserDetailsServiceImpl implements UserDetailsService { private final IMyUserService userService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return userService.getOne(new QueryWrapper<MyUser>().eq("username", username)); } }

MacLoginUrlAuthenticationEntryPoint

package com.example.springbootsecurity.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * springboot-study
 * 

* * @author : ZhangYuJie * @date : 2022-05-15 17:04 **/
@Component public class MacLoginUrlAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); httpServletResponse.setContentType("application/json;charset=utf-8"); PrintWriter writer = httpServletResponse.getWriter(); writer.write(new ObjectMapper().writeValueAsString("未登录!")); } }

MyAccessDeniedHandler

package com.example.springbootsecurity.config;

/**
 * springboot-study
 * 

* * @author : ZhangYuJie * @date : 2022-05-15 17:04 **/
import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * springboot-study *

权限不足回调

* * @author : ZhangYuJie * @date : 2022-05-15 17:05 **/
@Component public class MyAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException { httpServletResponse.setContentType("application/json;charset=utf-8"); httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); PrintWriter writer = httpServletResponse.getWriter(); writer.write(new ObjectMapper().writeValueAsString("权限不足")); } }

MyLogoutSuccessHandler

package com.example.springbootsecurity.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * springboot-study
 * 

退出回调

* * @author : ZhangYuJie * @date : 2022-05-15 17:05 **/
@Component public class MyLogoutSuccessHandler implements LogoutSuccessHandler { @Override public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setContentType("application/json;charset=utf-8"); PrintWriter writer = httpServletResponse.getWriter(); writer.write(new ObjectMapper().writeValueAsString("退出成功")); } }

JWT的工具类

package com.example.springbootsecurity.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Date;
import java.util.HashMap;

/**
 * springboot-study
 * 

JWT工具类

* * @author : ZhangYuJie * @date : 2022-05-15 16:54 **/
@Slf4j public class JwtTokenUtils { public static final String TOKEN_HEADER = "Authorization"; public static final String TOKEN_PREFIX = "Bearer "; private static final String SECRET = "jwtsecretdemo"; private static final String ISS = "echisan"; /** * 过期时间是3600秒,既是1个小时 */ private static final long EXPIRATION = 3600L; /** * 选择了记住我之后的过期时间为7天 */ private static final long EXPIRATION_REMEMBER = 604800L; // 添加角色的key private static final String ROLE_CLAIMS = "rol"; /** * 修改一下创建token的方法 * * @param username * @param role * @param isRememberMe * @return */ public static String createToken(String username, String role, boolean isRememberMe) { String token = null; try { long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION; HashMap<String, Object> map = new HashMap<>(); map.put(ROLE_CLAIMS, role); token = Jwts.builder() .signWith(SignatureAlgorithm.HS512, SECRET) // 这里要早set一点,放到后面会覆盖别的字段 .setClaims(map) .setIssuer(ISS) .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)) .compact(); } catch (ExpiredJwtException e) { log.error("token异常:{}", e.getMessage(), e); } return token; } /** * 从token中获取用户名 * * @param token * @return */ public static String getUsername(String token) { return getTokenBody(token).getSubject(); } /** * 从token中获取roles * * @param token * @return */ public static String getUserRole(String token) { return (String) getTokenBody(token).get(ROLE_CLAIMS); } /** * 是否已过期 * * @param token * @return */ public static boolean isExpiration(String token) { return getTokenBody(token).getExpiration().before(new Date()); } private static Claims getTokenBody(String token) { return Jwts.parser() .setSigningKey(SECRET) .parseClaimsJws(token) .getBody(); } public static void main(String[] args) { BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); String user = encoder.encode("admin"); System.out.println(user); } }

打这security相关配置就基本结束了

代码 entity

package com.example.springbootsecurity.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * springboot-study
 * 

* * @author : ZhangYuJie * @date : 2022-05-15 16:56 **/
@Data @EqualsAndHashCode(callSuper = false) @TableName("account") public class MyUser implements Serializable, UserDetails { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private int id; private String username; private String password; /** * 1:启用 , 0:禁用 */ @TableField(exist = false) private Integer enabled = 1; /** * 1:锁住 , 0:未锁 */ @TableField(exist = false) private Integer locked = 0; private String role; @TableField(exist = false) private String token; /** * 授权 * @return */ @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<SimpleGrantedAuthority> authorities = new ArrayList<>(); SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role); authorities.add(authority); return authorities; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return locked == 0; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return enabled == 1; } }

mapper

package com.example.springbootsecurity.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springbootsecurity.entity.MyUser;
import org.apache.ibatis.annotations.Mapper;

/**
 * springboot-study
 * 

* * @author : ZhangYuJie * @date : 2022-05-15 16:59 **/
@Mapper public interface MyUserMapper extends BaseMapper<MyUser> { }

service、impl

package com.example.springbootsecurity.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springbootsecurity.entity.MyUser;
import com.example.springbootsecurity.mapper.MyUserMapper;
import com.example.springbootsecurity.service.IMyUserService;
import org.springframework.stereotype.Service;

/**
 * springboot-study
 * 

* * @author : ZhangYuJie * @date : 2022-05-15 17:00 **/
@Service public class MyUserServiceImpl extends ServiceImpl<MyUserMapper, MyUser> implements IMyUserService { }
package com.example.springbootsecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springbootsecurity.entity.MyUser;
import com.example.springbootsecurity.service.IMyUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * springboot-study
 * 

* * @author : ZhangYuJie * @date : 2022-05-15 16:48 **/
@Slf4j @Service @RequiredArgsConstructor public class UserDetailsServiceImpl implements UserDetailsService { private final IMyUserService userService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return userService.getOne(new QueryWrapper<MyUser>().eq("username", username)); } }
package com.example.springbootsecurity.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.springbootsecurity.entity.MyUser;

/**
 * springboot-study
 * 

* * @author : ZhangYuJie * @date : 2022-05-15 16:55 **/
public interface IMyUserService extends IService<MyUser> { }

controller

package com.example.springbootsecurity.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * springboot-study
 * 

* * @author : ZhangYuJie * @date : 2022-05-15 17:01 **/
@RestController public class UserController { @RequestMapping("/all") String all() { return "在WebSecurityConfig中配置了放行,任何人都可以进行访问"; } @PreAuthorize("permitAll()") @RequestMapping("/test") String test() { return "所有登录的人都可以访问"; } @PreAuthorize("hasRole('USER')") @RequestMapping("/user/userList") String userList() { return "role: user"; } @PreAuthorize("hasRole('ADMIN')") @RequestMapping("/admin/updateUser") String updateUser() { return "role: admin"; } @PreAuthorize("hasRole('SUPER_ADMIN')") @RequestMapping("/admin/superAdmin") String superAdmin() { return "role: superAdmin"; } @PreAuthorize("hasAnyRole('ADMIN','USER')") @RequestMapping("/userAndAdmin") String userAndAdminTest() { return "role: admin and user"; } @PreAuthorize("hasAnyRole('ADMIN')or hasAnyRole('SUPER_ADMIN')") @RequestMapping("/AdminAndSuperAdminTest") String AdminAndSuperAdminTest() { return "role: admin and super_admin"; } /** * hasAnyAuthority() 也是可以多个字符串 权限验证,可以不跟ROLE_前缀 * @return */ @PreAuthorize("hasAuthority('TEST') ") @RequestMapping("/ceshi2") String ceshi2() { return "hasAuthority:权限验证,不过查的也是role那个字段,不过不用拼接上ROLE而已"; } }

相关代码到这就结束了 以上代码地址

总结
Security框架和SpringBoot集成,其实上手非常快快,但是如果要想研究的比较深的话,我觉得是比较困难的,security是属于一个重量级的框架,里面很多东西非常多。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/923039.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存