目录
问题内容
解决方法
首页 Java Spring Security 在其余服务中获取经过身份验证和未经过身份验证的用户的用户信息

Spring Security 在其余服务中获取经过身份验证和未经过身份验证的用户的用户信息

Feb 08, 2024 pm 11:00 PM
spring security

在开发Web应用程序时,安全性是一个重要的考虑因素。为了保护用户数据和防止未经授权的访问,我们需要使用一种可靠的身份验证和授权机制。Spring Security是一个功能强大且广泛使用的安全框架,它提供了一套完整的解决方案来保护我们的应用程序。在本文中,我们将探讨如何在Spring Security中获取经过身份验证和未经过身份验证的用户的用户信息。php小编百草将向您展示如何利用Spring Security的功能,获取用户信息以及在不同服务之间共享用户信息的方法。无论您是初学者还是有经验的开发人员,本文都将为您提供有关Spring Security的详细信息,并帮助您提升应用程序的安全性。

问题内容

我有一个 spring rest 服务,我想将它用于经过身份验证和未经身份验证的用户。如果用户经过身份验证,我想从 securitycontextholder.getcontext().getauthentication() 获取用户信息。

  • 如果我使用 .antmatchers("/app/rest/question/useroperation/list/**").permitall() 在 ouath2 配置中,如下所示,然后我可以获取用户信息 经过身份验证的用户,但未经过身份验证的用户会出现 401 错误。
  • 如果我 .antmatchers("/app/rest/question/useroperation/list/**").permitall() 并忽略 websecurity 中的 url web.ignoring()..antmatchers("/app/rest/question/useroperation/list/**")securityconfiguration 中如下所示,然后所有用户都可以调用 服务,但我无法从 securitycontext 获取用户信息。

如何配置我的 spring security 来调用经过身份验证和未经身份验证的用户的 url,并在用户登录时从 securitycontext 获取用户信息。

@configuration
@enableresourceserver
protected static class resourceserverconfiguration extends resourceserverconfigureradapter {

    @inject
    private http401unauthorizedentrypoint authenticationentrypoint;

    @inject
    private ajaxlogoutsuccesshandler ajaxlogoutsuccesshandler;

    @override
    public void configure(httpsecurity http) throws exception {
        http
                .exceptionhandling()
                .authenticationentrypoint(authenticationentrypoint)
                .and()
                .logout()
                .logouturl("/app/logout")
                .logoutsuccesshandler(ajaxlogoutsuccesshandler)
                .and()
                .csrf()
                .requirecsrfprotectionmatcher(new antpathrequestmatcher("/oauth/authorize"))
                .disable()
                .headers()
                .frameoptions().disable()
                .sessionmanagement()
                .sessioncreationpolicy(sessioncreationpolicy.stateless)
                .and()
                .authorizerequests()
                .antmatchers("/views/**").permitall()
                .antmatchers("/app/rest/authenticate").permitall()
                .antmatchers("/app/rest/register").permitall()
                .antmatchers("/app/rest/question/useroperation/list/**").permitall()
                .antmatchers("/app/rest/question/useroperation/comment/**").authenticated()
                .antmatchers("/app/rest/question/useroperation/answer/**").authenticated()
                .antmatchers("/app/rest/question/definition/**").hasanyauthority(authoritiesconstants.admin)
                .antmatchers("/app/rest/logs/**").hasanyauthority(authoritiesconstants.admin)
                .antmatchers("/app/**").authenticated()
                .antmatchers("/websocket/tracker").hasauthority(authoritiesconstants.admin)
                .antmatchers("/websocket/**").permitall()
                .antmatchers("/metrics/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/health/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/trace/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/dump/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/shutdown/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/beans/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/info/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/autoconfig/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/env/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/trace/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/api-docs/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/protected/**").authenticated();

    }

}
登录后复制

安全配置

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Inject
    private UserDetailsService userDetailsService;


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new StandardPasswordEncoder();
    }

    @Inject
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
            .antMatchers("/bower_components/**")
            .antMatchers("/fonts/**")
            .antMatchers("/images/**")
            .antMatchers("/scripts/**")
            .antMatchers("/styles/**")
            .antMatchers("/views/**")
            .antMatchers("/i18n/**")
            .antMatchers("/swagger-ui/**")
            .antMatchers("/app/rest/register")
            .antMatchers("/app/rest/activate")
            .antMatchers("/app/rest/question/useroperation/list/**")
            .antMatchers("/console/**");
    }


    @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
    private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }

    }
}
登录后复制

解决方法

permitall() 仍然需要 authentication 对象出现在 securitycontext 中。

对于非 oauth 用户,这可以通过启用匿名访问来实现:

@override
public void configure(httpsecurity http) throws exception {
   http
//some configuration
     .and()
        .anonymous() //allow anonymous access
     .and()
        .authorizerequests()
           .antmatchers("/views/**").permitall()
//other security settings
登录后复制

匿名访问将添加额外的过滤器:anonymousauthenticationfilter到填充anonymousauthenticationtoken作为身份验证信息的过滤器链,以防securitycontext中没有authentication对象

我有这个安全配置用于通过/public/authphpcnendcphp检查authuser中文:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().authorizeRequests()
           .antMatchers("/api/skills/**", "/api/profile/**", "/api/info/**").authenticated()
           .antMatchers("/api/**").hasAuthority(Role.ROLE_ADMIN.getAuthority())
           .antMatchers("/public/auth").permitAll()
           .and().httpBasic()
           .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
           .and().csrf().disable();
}

@GetMapping(value = "/public/auth")
private ResponseEntity<User> getAuthUser(@AuthenticationPrincipal AuthUser authUser) {
    return authUser == null ? 
               ResponseEntity.notFound().build() :
               ResponseEntity.ok(authUser.getUser());
}
登录后复制

以上是Spring Security 在其余服务中获取经过身份验证和未经过身份验证的用户的用户信息的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Spring Security 6:cors() 已弃用并标记为删除 Spring Security 6:cors() 已弃用并标记为删除 Feb 10, 2024 pm 11:45 PM

我有下面的代码:publicSecurityFilterChainsecurityFilterChain(HttpSecurityhttp)throwsException{returnhttp.httpBasic().disable().cors().and().csrf().disable().authorizeHttpRequests().requestMatchers("

如何使用Java开发一个基于Spring Security SAML的单点登录系统 如何使用Java开发一个基于Spring Security SAML的单点登录系统 Sep 22, 2023 am 08:49 AM

如何使用Java开发一个基于SpringSecuritySAML的单点登录系统引言:随着互联网的快速发展,越来越多的应用程序被开发出来。在这些应用程序中,用户登录是最常见的功能之一。然而,对于企业级应用程序,用户需要在多个系统中进行登录,这将导致用户的登录体验非常糟糕。为了解决这个问题,单点登录系统(SingleSign-On,简称SSO)应运而生。简

GO 验证访问令牌(keycloak) GO 验证访问令牌(keycloak) Feb 09, 2024 am 09:30 AM

我正在尝试使用GO实现访问令牌验证。但我在网上看到的例子似乎只是用TOKEN_SECRET来验证它。但是我习惯了在Javaspring中编程,并且不需要使用TOKEN_SECRET。我只是提供jwk-set-uri,它会检查有效性(自动-安全过滤器等),我知道它与oauth服务器通信并进行此验证。Go中是否没有库可以通过向oauth服务器发出请求来检查令牌是否有效?我知道我知道我可以通过向oauth服务器的用户信息端点发出请求来手动进行此操作:http://localh

Spring Security权限控制框架使用指南 Spring Security权限控制框架使用指南 Feb 18, 2024 pm 05:00 PM

在后台管理系统中,通常需要访问权限控制,以限制不同用户对接口的访问能力。如果用户缺乏特定权限,则无法访问某些接口。本文将用waynboot-mall项目举例,给大家介绍常见后管系统如何引入权限控制框架SpringSecurity。大纲如下:waynboot-mall项目地址:https://github.com/wayn111/waynboot-mall一、什么是SpringSecuritySpringSecurity是一个基于Spring框架的开源项目,旨在为Java应用程序提供强大和灵活的安

如何使用Java开发一个基于Spring Security OAuth2的单点登录系统 如何使用Java开发一个基于Spring Security OAuth2的单点登录系统 Sep 20, 2023 pm 01:06 PM

如何使用Java开发一个基于SpringSecurityOAuth2的单点登录系统引言:随着互联网的高速发展,越来越多的网站和应用程序需要用户进行登录,而用户却不希望为每个网站或应用程序都记住一个账号和密码。单点登录系统(SingleSign-On,简称SSO)能够解决这个问题,允许用户在一次登录后,无需重复认证就可以访问多个网站和应用程序。本文将介绍

Spring Security 在其余服务中获取经过身份验证和未经过身份验证的用户的用户信息 Spring Security 在其余服务中获取经过身份验证和未经过身份验证的用户的用户信息 Feb 08, 2024 pm 11:00 PM

我有一个springrest服务,我想将它用于经过身份验证和未经身份验证的用户。如果用户经过身份验证,我想从securitycontextholder.getcontext().getauthentication()获取用户信息。如果我使用.antmatchers("/app/rest/question/useroperation/list/**").permitall()在ouath2配置中,如下所示,然后我可以获取用户信息经过身份验证的用户,但未经过身份验证的用户会出现40

Java RESTful API 烹饪书:为每个应用程序打造完美的服务 Java RESTful API 烹饪书:为每个应用程序打造完美的服务 Mar 27, 2024 pm 12:11 PM

引言在当今互联互通的世界中,RESTfulapi已成为应用程序之间进行通信的关键机制。借助Java这一强大的编程语言,您可以构建高效、可扩展且维护良好的RESTfulAPI。第1章:RESTfulAPI基础RESTful架构的原则和最佳实践Http方法、状态代码和响应标头JSON和XML等数据格式第2章:设计和建模RESTfulAPIRESTfulAPI设计原则资源建模和URI设计版本控制和HATEOAS第3章:使用SpringBoot构建RESTfulAPISpringBoot简介和入门构建和

vue框架和springboot框架前后端怎么交互 vue框架和springboot框架前后端怎么交互 Apr 06, 2024 am 01:51 AM

Vue.js 和 Spring Boot 通过以下方式交互:RESTful API:Vue.js 使用 Axios 发送异步 HTTP 请求,Spring Boot 提供 RESTful API 实现。数据传递:数据通过请求和响应传递,如请求正文或查询参数。请求方法:GET、POST、PUT 和 DELETE 等 HTTP 请求方法用于指定操作。路由:Spring Boot @RequestMapping 注解定义控制器路由,Vue.js 使用 Vue Router 定义界面路由。状态管理:Vu