系列五、Spring Security中的认证 & 授权(前后端分离)

这篇具有很好参考价值的文章主要介绍了系列五、Spring Security中的认证 & 授权(前后端分离)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、Spring Security中的认证 & 授权(前后端分离)

1.1、MyWebSecurityConfigurerAdapter7002

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2024/1/11 21:50
 * @Description: Spring Security配置类
 */
@Configuration
public class MyWebSecurityConfigurerAdapter7002 extends WebSecurityConfigurerAdapter {

    @Resource
    private MyAuthenticationSuccessHandler7002 successHandler;
    @Resource
    private MyAuthenticationFailureHandler7002 failureHandler;
    @Resource
    private MyLogoutSuccessHandler logoutSuccessHandler;
    @Resource
    private MyAuthenticationEntryPoint authenticationEntryPoint;

    /**
     * 密码加密器
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    /**
     * 配置基于内存的用户
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("123456")
                .roles("admin")

                .and()

                .withUser("root")
                .password("123456")
                .roles("root");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/helloWorld")
                .permitAll()
                .anyRequest()
                .authenticated()

                .and()

                /**
                 * 登录成功 & 登录失败回调
                 */
                .formLogin()
                .loginPage("/login")
                .successHandler(successHandler)
                .failureHandler(failureHandler)

                .and()

                /**
                 * 注销登录回调
                 */
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(logoutSuccessHandler)
                .permitAll()

                .and()

                .csrf()
                .disable()

                /**
                 * 未认证回调
                 */
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint);
    }

}

1.2、MyAuthenticationSuccessHandler7002

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2024/1/12 09:55
 * @Description: 认证(登录)成功处理器
 */
@Component
public class MyAuthenticationSuccessHandler7002 implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        R r = R.ok().data(authentication.getPrincipal());
        out.write(new ObjectMapper().writeValueAsString(r));
        out.flush();
        out.close();
    }
}

1.3、MyAuthenticationFailureHandler7002

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/1/12 10:05
 * @Description: 认证(登录)失败处理器
 */
@Component
public class MyAuthenticationFailureHandler7002 implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        R r = R.error();
        if (exception instanceof LockedException) {
            r.data(SpringSecurityConstants.LOCKED_ERROR_MESSAGE);
        } else if (exception instanceof CredentialsExpiredException) {
            r.data(SpringSecurityConstants.CREDENTIALS_EXPIRED_ERROR_MESSAGE);
        } else if (exception instanceof AccountExpiredException) {
            r.data(SpringSecurityConstants.ACCOUNT_EXPIRED_ERROR_MESSAGE);
        } else if (exception instanceof DisabledException) {
            r.data(SpringSecurityConstants.DISABLED_ERROR_MESSAGE);
        } else if (exception instanceof BadCredentialsException) {
            r.data(SpringSecurityConstants.BAD_CREDENTIALS_ERROR_MESSAGE);
        } else if (exception instanceof AuthenticationServiceException) {
            r.data(SpringSecurityConstants.VERIFY_CODE_ERROR_MESSAGE);
        } else {
            r.data(SpringSecurityConstants.LOGIN_ERROR_COMMON_MESSAGE);
        }
        out.write(new ObjectMapper().writeValueAsString(r));
        out.flush();
        out.close();
    }
}

1.4、MyLogoutSuccessHandler7002

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2024/01/12 11:26
 * @Description: 注销登录处理器
 */
@Component
public class MyLogoutSuccessHandler7002 implements LogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        R r = R.ok().data(SpringSecurityConstants.LOGOUT_SUCCESS_MESSAGE);
        out.write(new ObjectMapper().writeValueAsString(r));
        out.flush();
        out.close();
    }

}

1.5、MyAuthenticationEntryPoint7002

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2024/01/12 11:27
 * @Description: 未认证处理方案(用户未登录就访问资源)
 */
@Component
public class MyAuthenticationEntryPoint7002 implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        R r = R.error(ResponseEnum.HTTP_UNAUTHORIZED_ERROR.getCode(),ResponseEnum.HTTP_UNAUTHORIZED_ERROR.getMessage());
        out.write(new ObjectMapper().writeValueAsString(r));
        out.flush();
        out.close();
    }

}

1.6、SpringSecurityConstants7002

/**
 * @Author 一叶浮萍归大海
 * @Description Spring Security认证 & 授权常量类
 * @Date 2024/01/12 10:06
 */
public class SpringSecurityConstants {

    public static final String LOGOUT_SUCCESS_MESSAGE = "注销成功!";
    public static final String LOCKED_ERROR_MESSAGE = "账户被锁定,请联系管理员!";
    public static final String CREDENTIALS_EXPIRED_ERROR_MESSAGE = "密码过期,请联系管理员!";
    public static final String ACCOUNT_EXPIRED_ERROR_MESSAGE = "账户过期,请联系管理员!";
    public static final String DISABLED_ERROR_MESSAGE = "账户被禁用,请联系管理员!";
    public static final String BAD_CREDENTIALS_ERROR_MESSAGE = "用户名或者密码错误,请重新输入!";
    public static final String VERIFY_CODE_ERROR_MESSAGE = "验证码错误!";
    public static final String LOGIN_ERROR_COMMON_MESSAGE = "登录失败,请联系管理员!";
}

1.7、R

/**
 * @Author 一叶浮萍归大海
 * @Description
 * @Date 2023/01/12 10:06
 */
@Data
public class R<T> {
    private Integer code;
    private String message;
    private T data;


    /**
     * 构造函数私有化
     */
    private R(){}

    /**
     * 返回成功结果
     * @return
     */
    public static R ok(){
        R r = new R();
        r.setCode(ResponseEnum.SUCCESS.getCode());
        r.setMessage(ResponseEnum.SUCCESS.getMessage());
        return r;
    }

    /**
     * 返回失败结果
     * @return
     */
    public static R error(){
        R r = new R();
        r.setCode(ResponseEnum.ERROR.getCode());
        r.setMessage(ResponseEnum.ERROR.getMessage());
        return r;
    }

    public static R error(int code, String msg) {
        R r = new R();
        r.setCode(code);
        r.setMessage(msg);
        return r;
    }

    /**
     * 设置特定的结果
     * @param responseEnum
     * @return
     */
    public static R setResult(ResponseEnum responseEnum){
        R r = new R();
        r.setCode(responseEnum.getCode());
        r.setMessage(responseEnum.getMessage());
        return r;
    }

    public R data(T entity) {
        this.setData(entity);
        return this;
    }

    /**
     * 设置特定的响应消息
     * @param message
     * @return
     */
    public R message(String message){
        this.setMessage(message);
        return this;
    }


    /**
     * 设置特定的响应码
     * @param code
     * @return
     */
    public R code(Integer code){
        this.setCode(code);
        return this;
    }
}

1.8、ResponseEnum

/**
 * @Author 一叶浮萍归大海
 * @Description
 * @Date 2023/5/30 15:55
 */
@Getter
@ToString
@AllArgsConstructor
public enum ResponseEnum {

    /**
     * 响应状态码 & 响应信息映射
     */
    SUCCESS(200, "成功!"),
    ERROR(201, "失败!"),
    SERVER_INTERNAL_ERROR(500, "服务器内部错误,请联系管理员!"),
    PARAMETER_VALIDATE_FAILED_ERROR(10001, "参数校验失败,请联系管理员!"),
    BUSINESS_ERROR(10002, "业务异常,请联系管理员"),

    // =================== Spring Cloud Alibaba Sentinel统一异常处理 ===================
    SENTINEL_FLOW_EXCEPTION(20001,"接口被限流,请联系管理员!"),
    SENTINEL_DEGRADE_EXCEPTION(20002,"接口被降级,请联系管理员!"),
    SENTINEL_PARAM_FLOW_EXCEPTION(20003,"热点参数限流,请联系管理员!"),
    SENTINEL_SYSTEM_BLOCK_EXCEPTION(20004,"触发系统保护规则,请联系管理员!"),
    SENTINEL_AUTHORITY_EXCEPTION(20005,"授权规则不通过,请联系管理员!"),

    // =================== Spring Security统一异常处理 ===================
    HTTP_UNAUTHORIZED_ERROR(401, "尚未登录,请登录!"),
    HTTP_FORBIDDEN_ERROR(403, "权限不足,请联系管理员!"),
    ;

    /**
     * 响应状态码
     */
    private Integer code;

    /**
     * 响应信息
     */
    private String message;

}

文章来源地址https://www.toymoban.com/news/detail-795705.html

到了这里,关于系列五、Spring Security中的认证 & 授权(前后端分离)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringCloud整合spring security+ oauth2+Redis实现认证授权

    在微服务构建中,我们一般用一个父工程来通知管理依赖的各种版本号信息。父工程pom文件如下: 在SpringCloud微服务体系中服务注册中心是一个必要的存在,通过注册中心提供服务的注册和发现。具体细节可以查看我之前的博客,这里不再赘述。我们开始构建一个eureka注册中

    2024年02月06日
    浏览(47)
  • Spring Security Oauth2.1 最新版 1.1.0 整合 gateway 完成授权认证(拥抱 springboot 3.1)

    目录 背景 demo地址 版本 Spring Boot 3.1 Spring Authorization Server 1.1.0 基础 spring security OAuth2 模块构成 授权方式 认证方式 集成过程 官方demo 代码集成 依赖 授权服务AuthorizationServerConfig配置 重要组件 测试 查看授权服务配置 访问授权服务 授权 回调 获取 access_token 获取用户信息 个性

    2024年02月08日
    浏览(51)
  • Spring Security Oauth2.1 最新版 1.1.0 整合 (基于 springboot 3.1.0)gateway 完成授权认证

    目录 背景 demo地址 版本 Spring Boot 3.1 Spring Authorization Server 1.1.0 基础 spring security OAuth2 模块构成 授权方式 认证方式 集成过程 官方demo 代码集成 依赖 授权服务AuthorizationServerConfig配置 重要组件 测试 查看授权服务配置 访问授权服务 授权 回调 获取 access_token 获取用户信息 个性

    2024年02月11日
    浏览(43)
  • 【深入浅出 Spring Security(十三)】使用 JWT 进行前后端分离认证(附源码)

    JWT 全称 Java web Token,在此所讲述的是 JWT 用于身份认证,用服务器端生成的JWT去替代原始的Session认证,以提高安全性。 JWT本质是一个Token令牌,是由三部分组成的字符串,分别是头部(header)、载荷(payload)和签名(signature)。头部一般包含该 JWT 的基本信息,例如所使用的

    2024年02月12日
    浏览(32)
  • 系列八、Spring Security中基于Mybatis Plus的用户认证 & 授权

           【上篇】文章介绍了基于Jdbc的用户认证 授权,虽然实现了在数据库中认证和授权的逻辑,但是底层都是Spring Security底层帮我们定义好的,扩展性不强,企业开发中,常用的持久化方案是MyBatis Plus,那么Spring Security中如何定义基于MyBatis Plus的方式进行认证授权呢?请看

    2024年01月18日
    浏览(42)
  • Spring Security对接OIDC(OAuth2)外部认证

    前后端分离项目对接OIDC(OAuth2)外部认证,认证服务器可以使用Keycloak。 后端已有用户管理和权限管理,需要外部认证服务器的用户名和业务系统的用户名一致才可以登录。 后台基于Spring Boot 2.7 + Spring Security 流程: 前台浏览器跳转到  后台地址 + /login/oauth2/authorization/my-oid

    2024年02月21日
    浏览(34)
  • 【Spring Security】Spring Security 认证与授权

    在前面的章节中,我们沿用了Spring Security默认的安全机制:仅有一个用户,仅有一种角色。在实际开发中,这自然是无法满足需求的。本章将更加深入地对Spring Security迚行配置,且初步使用授权机制。 3.1 默认数据库模型的认证与授权 3.1.1、资源准备 首先,在controller包下新建

    2024年02月05日
    浏览(46)
  • spring security认证授权流程

    认证和授权是任何安全体系中的两个主要功能,而在现代Web开发中,Spring Security是最受欢迎和广泛使用的安全框架之一。在本篇文章中,我们将全面介绍Spring Security的认证和授权机制,并提供详细的步骤和示例代码。  一、认证(Authentication) 认证的主要目的是验证用户的身

    2024年02月15日
    浏览(34)
  • Spring Boot OAuth2 认证服务器搭建及授权码认证演示

    本篇使用JDK版本是1.8,需要搭建一个OAuth 2.0的认证服务器,用于实现各个系统的单点登录。 这里选择Spring Boot+Spring Security + Spring Authorization Server 实现,具体的版本选择如下: Spirng Boot 2.7.14 , Spring Boot 目前的最新版本是 3.1.2,在官方的介绍中, Spring Boot 3.x 需要JDK 17及以上的

    2024年02月15日
    浏览(42)
  • Spring Gateway+Security+OAuth2+RBAC 实现SSO统一认证平台

    背景:新项目准备用SSO来整合之前多个项目的登录和权限,同时引入网关来做后续的服务限流之类的操作,所以搭建了下面这个系统雏形。 : Spring Gateway, Spring Security, JWT, OAuth2, Nacos, Redis, Danymic datasource, Javax, thymeleaf 如果对上面这些技术感兴趣,可以继续往下阅读 如

    2024年02月13日
    浏览(45)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包