标签: spring-security

spring security HTTP状态403-访问被拒绝

登录成功,但即使我授予了USER 的访问权限,Spring Security 也会阻止 url 。我该如何管理这件事?

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.inMemoryAuthentication().withUser("sahil").password("123")
                .roles("ADMIN","USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
        .antMatchers("/login").permitAll()
        .antMatchers("/welcome","/inventory/**","/sales/**").access("hasRole('USER')")
        .and()
        .csrf().disable();
    }
Run Code Online (Sandbox Code Playgroud)

登录控制器.java

    @Controller
public class LoginController {

    @RequestMapping(value = { "/", "/login" }, method = RequestMethod.GET)
    public String showLoginPage() {
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String handleUserLogin(ModelMap model, @RequestParam String name, @RequestParam String password) { …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-security access-denied

1
推荐指数
1
解决办法
1万
查看次数

当 @Scheduled 触发时,在 SecurityContext 中未找到 Authentication 对象?

我创建了一个Spring Boot应用程序,但在某些可以手动或通过@Scheduled注释触发的端点上遇到了问题。

我遇到的问题如下:

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException:在SecurityContext中找不到身份验证对象

SecurityContext如果进程调用 via ,是否有办法触发@Scheduled?

我是新手Spring Security,很难理解参考指南。我发现了一些类似的问题,但仍然无法理解如何将答案应用于我的案例。

我的例子MyController:

@Secured("ROLE_ADMIN")
@RestController
@RequestMapping(value = "/api")
public class MyController {

    @Scheduled(cron = "* * * * * *")
    @GetMapping(path="/data")
    public void getData() {
        // Do some operations
    }
}
Run Code Online (Sandbox Code Playgroud)

java spring spring-security spring-scheduled spring-boot

1
推荐指数
1
解决办法
6172
查看次数

Spring Security 添加到 Spring Boot 应用程序导致异常

我正在尝试将 Spring Security 添加到 Spring Boot 应用程序中。除非存在依赖项版本问题,否则我的设置中是否还有其他内容可能会丢失,从而导致下面的异常跟踪。我还添加了一些来自 keycloak 的依赖项,我在下面复制了这些依赖项。

聚甲醛

    <dependency>
        <groupId>org.keycloak</groupId>
        <artifactId>keycloak-spring-boot-starter</artifactId>
        <version>7.0.1</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
        <version>1.5.3.RELEASE</version>
    </dependency>


    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>5.2.1.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>5.2.1.RELEASE</version>
    </dependency>

<dependencyManagement>
    <dependencies>
        <dependency>
            <!--Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.5.5.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>

        <dependency>
            <groupId>org.keycloak.bom</groupId>
            <artifactId>keycloak-adapter-bom</artifactId>
            <version>3.3.0.Final</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
Run Code Online (Sandbox Code Playgroud)

我添加了以下类作为 spring security 和 keycloak 设置的一部分:

import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.keycloak.adapters.springsecurity.KeycloakSecurityComponents;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security spring-boot keycloak

1
推荐指数
1
解决办法
6478
查看次数

找不到类 org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken 的提供程序

我创建了三个应用程序“spring cloud gateway(8081)”、“spring oauth2 auth server(8094)”和“spring oauth2 Resource server(8097)”。

\n\n

当我想请求资源服务器时,首先我需要请求 gw,它转发到 oauth 服务器,然后我登录那里(oauth 也有 spring 安全层)。成功登录后,它会重定向到后台 gw 服务器,例如http://localhost:8081/login/oauth2/code/gateway?code=6ldKVF&state=0WvvWdTs8G_XchSTQKqgokua_XDVQziqVZ_VXLMqIS0%3D url。然后,屏幕上发生错误。

\n\n

当我在身份验证服务器成功登录时,网关服务器控制台中有一个跟踪日志:

\n\n
\n

2020-01-17 17:52:11.825 跟踪 11336 --- [ctor-http-nio-4]\n oshttp.codec.json.Jackson2JsonDecoder :[21762c89] 已解码\n [{access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOls ib2F1dGgyLXJlc291cmNlIl0sInVzZXJfbmFtZSI6ImRnIiwic2NvcGUIOlsiY3VzdG9tX21vZCJdLCJleHAiOjE1NzkyNzI3NDEsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiowu zYzQ2YTQtMDJiZi00MTgwLTg1ZTktMGJhOTM0MjBhYjg4IiwiY2xpZW50X2lkIjoiZmlyc3QtY2xpZW50In0.xdWGm420tvp2Rzq0AyCgOTcDuKvP- V6JFd76KmJJf7o,\n token_type=承载,\n refresh_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsib2F1dGgyLXJlc291cmNlIl0sInVzZXJfbmFtZSI6ImRnIiwic2NvcGUiOlsiY3Vz dG9tX21vZCJdLCJhdGkiOiI5ZTNjNDZhNC0wMmJmLTQxODAtODVLOS0wYmE5MzQyMGFiODgiLCJleHAiOjE1NzkyNzI3NTEsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiYzeyNWexM2It MmMzYS00ZGM0LWJjODgtZDc4ZDk1ZTljNzQ5IiwiY2xpZW50X2lkIjoiZmlyc3QtY2xpZW50In0.KhRIy7wOH2IsswDZ_AIXVFdtu6JZqtiLBZGZIypeNRw,\n expires_in=9,scope=custom_mod,\n jti=9e3 c46a4-02bf-4180-85e9-0ba93420ab88}]

\n
\n\n

当我解码以访问令牌 jwt 时,结果如下。

\n\n
{\n"aud": [\n"oauth2-resource"\n],\n"user_name": "dg",\n"scope": [\n"custom_mod"\n],\n"exp": 1579272741,\n"authorities": [\n"ROLE_ADMIN"\n],\n"jti": "9e3c46a4-02bf-4180-85e9-0ba93420ab88",\n"client_id": "first-client"\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我想,我缺少一些在网关服务器或 oauth 服务器中实现的部分,但我找不到。因为当我尝试使用 okta 而不是我的自定义身份验证服务器时,没有错误。

\n\n

网关应用程序.properties

\n\n
server.port=8081\nspring.security.oauth2.client.registration.gateway.client-id=first-client\nspring.security.oauth2.client.registration.gateway.client-secret=noonewilleverguess\nspring.security.oauth2.client.registration.gateway.authorization-grant-type=authorization_code\nspring.security.oauth2.client.registration.gateway.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}\n\nspring.security.oauth2.client.provider.gateway.authorization-uri=http://localhost:8094/oauth/authorize\nspring.security.oauth2.client.provider.gateway.token-uri=http://localhost:8094/oauth/token?scope=custom_mod\nspring.security.oauth2.client.provider.gateway.user-info-uri=http://localhost:8094/userinfo\nspring.security.oauth2.client.provider.gateway.user-name-attribute=name\n\nlogging.level.root=trace\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是屏幕错误消息:

\n\n
\n

1 月 17 日星期五 17:28:11 EET 2020 …

spring-security spring-security-oauth2 spring-cloud spring-oauth2 spring-cloud-gateway

1
推荐指数
1
解决办法
4749
查看次数

Spring Security - 编码密码看起来不像 BCrypt

我无法使用正确的详细信息登录,因为程序不断指出编码的密码看起来不像 bcrypt。有谁知道如何解决这个问题?我正在使用 JDBC 身份验证。

我也有正确的数据库表,有足够的空间用于编码密码。我不确定哪里出了问题。

JSP 表单: <form:form method="post" modelAttribute="user" action="${pageContext.request.contextPath}/processLogin">

                <div class="form-group">
                    <div class="form-label-group">
                        <label for="inputUser">Username: </label> <input name="username"
                            type="text" path="username" id="inputUser" class="form-control"
                            placeholder="Username" required="required" autofocus="autofocus">
                    </div>
                </div>
                
                <div class="form-group">
                    <div class="form-label-group">
                        <label for="inputPassword">Password: </label> 
                        <input name="username" type="password" path="password"
                            id="inputPassword" class="form-control" placeholder="Password"
                            required="required">
                    </div>
                </div>
                
                <div class="form-group">
                    <div class="checkbox">
                        <label> <input type="checkbox" value="remember-me">
                            Remember Password
                        </label>
                    </div>
                </div>
                
                <input type="submit" value="Login"/>
                    
            </form:form>
Run Code Online (Sandbox Code Playgroud)

安全配置:

@Autowired
private DataSource securityDataSource;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.jdbcAuthentication().dataSource(securityDataSource).passwordEncoder(passwordEncoder());
}

@Override
protected …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-security

1
推荐指数
1
解决办法
6741
查看次数

Keycloak得到401错误,但是spring security不处理这个错误

问题如下。我通过 Keycloak Bearer Spring 安全性实现了登录,如下所示

public class KeycloakSecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter {

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
    keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
    auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Override
public void configure(HttpSecurity http) throws Exception {
    super.configure(http);
    http.sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .sessionAuthenticationStrategy(sessionAuthenticationStrategy())
            .and()
            .csrf().disable()
            .addFilterBefore(keycloakPreAuthActionsFilter(), LogoutFilter.class)
            .addFilterBefore(keycloakAuthenticationProcessingFilter(),               X509AuthenticationFilter.class)
            .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
            .and()
            .authorizeRequests().antMatchers(Constants.API_BASE_PATH + "/**").authenticated();
    }

}
Run Code Online (Sandbox Code Playgroud)

@ExceptionHandler当我将授权请求标头发送为空时,keycloak 会抛出错误 401。我无法像这样捕获错误:

@ExceptionHandler(RuntimeException.class)
protected ResponseEntity<Object> keycloakAuthenticationExceptionn(RuntimeException ex) {
    return buildResponseEntity(new ErrorResponseWrapper(BAD_REQUEST,new 
     MessageResponse(ex.getLocalizedMessage()),ex,ErrorCode.NOT_AUTHORIZED));
}
Run Code Online (Sandbox Code Playgroud)

spring spring-security spring-boot keycloak

1
推荐指数
1
解决办法
4730
查看次数

Spring Boot 2 Actuator 端点在 GET 请求时返回 405

我正在配置 spring Boot 执行器,但 /actuator 和 /health 端点在每个 GET 请求中返回 405。

我打开了整个安全机制,但它不起作用:

management.endpoints.jmx.exposure.exclude=*
management.endpoints.web.exposure.include=health,info,beans,env
management.endpoint.health.enabled=true
management.security.enabled=false
management.endpoint.beans.cache.time-to-live=10s
management.endpoints.web.cors.allowed-origins=*
management.endpoints.web.cors.allowed-methods=GET,POST
Run Code Online (Sandbox Code Playgroud)

我添加了以下配置

@Configuration(proxyBeanMethods = false)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/health", "/actuator").permitAll().and().csrf().disable();
    super.configure(http);
}
Run Code Online (Sandbox Code Playgroud)

}

因此,我按照教程进行操作,看起来非常简单,我不明白为什么在默认 GET 请求上收到此 405。当我使用 cURL 调用端点时:

 curl http://localhost:8080/sm-integration/health -v --> 405
 curl -X POST http://localhost:8080/sm-integration/health -v --> 400
Run Code Online (Sandbox Code Playgroud)

我不明白在执行 POST 时出现 400 Bad Request。文档指出 /health 是最基本和开放的端点,应该作为 GET 调用来调用。那么为什么是405呢?

更新 收到几个答案后,我设置了如下配置:

@Override
public void configure(HttpSecurity http) throws Exception …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security spring-boot spring-boot-actuator

1
推荐指数
1
解决办法
2121
查看次数

将请求方法与 Spring Security 的 Kotlin DSL 相匹配

Spring Security 提供了 Kotlin DSL 以便于配置。这是Spring 博客中的一个示例:

override fun configure(http: HttpSecurity?) {
    http {
        httpBasic {}
        authorizeRequests {
            authorize("/greetings/**", hasAuthority("ROLE_ADMIN"))
            authorize("/**", permitAll)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我只想允许对特定路径的 POST 请求。在Java中,你可以这样做:

http
  .httpBasic().and()
  .authorizeRequests()
    .antMatchers(HttpMethod.POST, "/greetings").hasRole("ADMIN");
Run Code Online (Sandbox Code Playgroud)

有使用 Kotlin DSL 的示例吗?

spring spring-security kotlin kotlin-dsl

1
推荐指数
1
解决办法
1536
查看次数

AWS Cognito 在尝试登录时出现 BadRequest 错误

我试图实现 AWS cognito spring boot 示例,如此处所述。

我在单击“使用 Amazon Cognito 登录”时收到以下错误:

{"code":"BadRequest","message":"The server did not understand the operation that was requested.","type":"client"}
Run Code Online (Sandbox Code Playgroud)

URI 是:

https://cognito-idp.{region}.amazonaws.com/{my-pool-id}/authorize?response_type=code&client_id={my-client-id}&scope=openid&state=NHfXN1aWjqUWiRBp0FZzIoZYHx-EmcuUp8sGDKUaODs%3D&redirect_uri=http://localhost:8080/login/oauth2/code/cognito&nonce=CgC_P_GCnLlHQ4W_9nT04hzwkjaDdPGs7OaLaklP0wU
Run Code Online (Sandbox Code Playgroud)

以下配置是我自己在排查问题时验证的。

  1. 客户端 ID、客户端密码、池 ID、区域等与我的 AWS 控制台中的配置完全相同。这里没有错误。

  2. 我正在使用 Cognito 提供的 UI 进行登录。域已添加并验证 Cognito UI 正在重定向到登录屏幕。

  3. 应用程序客户端设置中的回调 URI 与我的配置中的重定向 ui 相同。

我的示例配置文件链接到此处以供参考。

你能告诉我这里出了什么问题吗?我在这里错过了什么吗?

spring spring-security amazon-web-services spring-boot amazon-cognito

1
推荐指数
1
解决办法
1万
查看次数

为什么 PermitAll() 返回 403 Spring Security?

我创建了一种在数据库中保存用户详细信息的方法,并且我还有一个在端点 /register 处公开的控制器。我想让 /register 端点可供所有人使用。我已经使用了 spring security 并为 /register 端点授予了所有权限。


@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final UserDetailsServiceImpl userDetailsService;

    @Autowired
    public WebSecurityConfiguration(UserDetailsServiceImpl userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests(
                request -> request.antMatchers(HttpMethod.POST,"/register").permitAll()
                .anyRequest().authenticated()
            );
    }

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

Run Code Online (Sandbox Code Playgroud)

有人可以解释或帮助我解决为什么 allowedAll 在我的情况下不起作用吗?根据我编写的代码,/register 端点应该返回用户详细信息,但它返回 403。/register 端点是一个休息端点,它将用户详细信息作为输入,并在详细信息持久化后返回用户详细信息作为输出。数据库。

@Slf4j
@RestController
public class RegistrationController {

    private final …
Run Code Online (Sandbox Code Playgroud)

java spring-security spring-boot

1
推荐指数
1
解决办法
2965
查看次数