我现在开始学习Spring Security,但遇到了麻烦。我编写了配置类,从数据库获取数据等,但在我的网页中,我在登录后看到消息“用户帐户已锁定”和 url 中的错误参数。
MessengerApplication.java
@SpringBootApplication
public class MessengerApplication {
public static void main(String[] args) {
SpringApplication.run(MessengerApplication.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
MainPageController.java
@RestController
public class MainPageController {
@RequestMapping("/")
public ModelAndView greeting() {
Map<String, Object> model = new HashMap<>();
model.put("data", "world");
return new ModelAndView("main_page", model);
}
}
Run Code Online (Sandbox Code Playgroud)
安全配置.java
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserServiceImpl userService;
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider
= new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userService);
authProvider.setPasswordEncoder(encoder());
return …Run Code Online (Sandbox Code Playgroud) 我正在开发 Spring 应用程序,但在使用 Swagger 和 Spring Security 时遇到了一些问题。我必须添加一个特定的配置来允许几乎所有访问(CORS),到目前为止它运行良好,但不知何故它阻止了 Swagger....
这是我的 SwaggerConfiguration.java
@Configuration
@EnableSwagger2
@SwaggerDefinition(
info = @Info(
description = "Web Service",
version = "V0.0.1",
title = "Web Service",
contact = @Contact(
name = "Me",
email = "dev@me.com",
url = "https://www.me.com/"
)
),
consumes = {"application/json"},
produces = {"application/json"},
schemes = {SwaggerDefinition.Scheme.HTTP, SwaggerDefinition.Scheme.HTTPS}
)
public class SwaggerConfiguration {
/** List of Swagger endpoints (used by {@code WebSecurityConfig}) */
static final String[] SWAGGER_ENDPOINTS = {
"/v2/api-docs",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**" …Run Code Online (Sandbox Code Playgroud) 我用 jwt 加 oauth2 (在内存中)实现了 spring boot。
这里的令牌位于内存中而不是数据库中。
但是当我使用时tokenStore.findTokensByClientId(clientId),它在下面的情况下返回空白数组
例子
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
static final String CLIEN_ID = "vishvas-client";
static final String CLIENT_SECRET = "$2a$10$kfH4W.jyBuqvX5TLu.OfbOEUtScm4V9FEUDvGI8AWPaqObUOQ7HJ2"; // vishvas-secret
static final String GRANT_TYPE_PASSWORD = "password";
static final String AUTHORIZATION_CODE = "authorization_code";
static final String REFRESH_TOKEN = "refresh_token";
static final String IMPLICIT = "implicit";
static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS …Run Code Online (Sandbox Code Playgroud) 我正在开发一个基于 Spring boot 的 Web 应用程序,主页包含一个带有登录和注册链接的 boostrap 导航栏。
用户登录后(通过单击主页中的登录链接),他们将再次重定向到主页(除非他们在 Spring Security 启动 A&A 之前访问任何其他链接)。在重定向时,我想隐藏导航栏中的登录和注册链接,并在其位置显示注销链接。因为我想在应用程序的所有页面中插入导航栏。
我想知道当要求重定向到同一页面时执行此操作的最佳/标准方法是什么。
我能想到的一种解决方案是从 spring security 检查并获取 user-principal 对象,将其传递给 thymeleaf 模板,并检查 thymeleaf 模板的请求属性中是否存在 userprincipal 对象,这意味着用户已登录然后我可以隐藏(不渲染)登录和注册链接以及显示(渲染)注销链接。如果没有,则显示登录和注册链接并隐藏注销链接。我想知道,这是正确的方法吗?这对我来说就像是一种黑客攻击,因此想知道是否有任何标准方法可以做到这一点。
spring-mvc spring-security thymeleaf spring-boot bootstrap-4
我正在尝试在 Spring Boot 中实现 JWT。出于某些调试目的,我需要 H2 控制台。
所以在我的WebSecurityConfiguration中,我写道:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
//httpSecurity.headers().frameOptions().disable();
httpSecurity.authorizeRequests().antMatchers("/h2").permitAll();
httpSecurity
.csrf().disable()
.authorizeRequests()
.antMatchers("/auth/check/username").permitAll()
.antMatchers("/auth/signup").permitAll()
.antMatchers("/auth/login").permitAll()
.anyRequest().authenticated().and()
.exceptionHandling().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
Run Code Online (Sandbox Code Playgroud)
在我的应用程序属性中,我有以下配置:
spring.h2.console.enabled=true
spring.h2.console.path=/h2
Run Code Online (Sandbox Code Playgroud)
当我点击“:8080/h2”时,它给了我403。
所以问题仍然是,如何正确配置 Spring Boot Web Security。
包含后/h2/**,我得到这个用户界面:
我正在使用 Java Spring Boot 和 Vaadin 框架在 Tomcat 上部署 Web 应用程序。我正在使用 Spring Security 与 Okta 进行通信,但在部署战争时遇到问题。
这是我的 pom.xml :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test.dashboard</groupId>
<artifactId>test-custom-dashboard</artifactId>
<name>Custom dashboard</name>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<java.version>8</java.version>
<vaadin.version>14.5.3</vaadin.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
</parent>
<repositories>
<!-- The order of definitions matters. Explicitly defining central here to make sure it has the highest priority. -->
<!-- Main Maven repository -->
<repository>
<id>central</id>
<url>https://repo.maven.apache.org/maven2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<!-- Repository used by many …Run Code Online (Sandbox Code Playgroud) 我正在开发一个 Spring Boot 2.5.0 Web 应用程序,并使用 Thymeleaf 进行 Spring Security 表单登录。我正在寻找有关如何使用 Spring Security 表单登录实现两因素身份验证(2FA)的想法。
要求是当用户使用他的用户名和密码登录时。在登录表单中,如果用户名和密码验证成功,则应将短信代码发送到用户注册的手机号码,并应在另一个页面上要求用户输入短信代码。如果用户正确获取短信代码,他应该被转发到安全的应用程序页面。
在登录表单上,除了用户名和密码外,还要求用户输入验证码图像中的文本,该文本使用SimpleAuthenticationFilter扩展的验证UsernamePasswordAuthenticationFilter。
这是当前的SecurityConfiguration
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsServiceImpl userDetailsService;
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers(
"/favicon.ico",
"/webjars/**",
"/images/**",
"/css/**",
"/js/**",
"/login/**",
"/captcha/**",
"/public/**",
"/user/**").permitAll()
.anyRequest().authenticated()
.and().formLogin()
.loginPage("/login")
.permitAll()
.defaultSuccessUrl("/", true)
.and().logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.deleteCookies("JSESSONID")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout")
.permitAll()
.and().headers().frameOptions().sameOrigin()
.and().sessionManagement()
.maximumSessions(5)
.sessionRegistry(sessionRegistry())
.expiredUrl("/login?error=5");
}
public SimpleAuthenticationFilter authenticationFilter() throws …Run Code Online (Sandbox Code Playgroud) spring-security two-factor-authentication thymeleaf spring-boot
专家,,
我有一个 Spring Boot 2.5.5 应用程序(嵌入式 tomcat),我必须在其中配置基本身份验证。
这是我的课程,可以为我完成工作
@Component
@EnableWebSecurity
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我只需要在浏览器中输入用户/密码一次,它就适用于任何后续请求。此外,在服务器重新启动后我不需要提供新的用户名/密码,这让我抓狂 - 应用程序仍然有效,我可以访问我的 API/页面。
即使我假设浏览器以某种方式保存用户名和密码,一旦服务器因密码更改而重新启动,它就不应该工作 - 不是吗?
更新二:
按照M. Deinum的建议,我将会话设置为无状态,并且成功了。然后,我继续使用 InMemoryUserDetailsManager 实现基本身份验证,并添加以下代码,我们再次回到同一问题。凭据似乎再次存储在会话中,我不需要为后续请求传递它们。
@Autowired
public ApplicationSecurityConfig(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Override
@Bean
protected UserDetailsService userDetailsService() {
UserDetails user = User
.builder()
.username("admin")
.password(passwordEncoder.encode("admin"))
.roles("ADMINISTRATOR")
.build();
return new InMemoryUserDetailsManager(user);
}
Run Code Online (Sandbox Code Playgroud) 我是 springboot 的新手,并试图实现安全性,其中没有过滤器应用于我的登录、注册和主页 url。
我使用的是springboot 2.7.1
我希望antMatchers("/**/signup").permitAll()不受任何安全过滤器的影响。
调试后,我发现我的注册网址被命中,用户详细信息被保存,但我的 AuthorizationFilter 也被执行。
这是我的 SecurityFilterChain :
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder=http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userLoginService).passwordEncoder(bCryptPasswordEncoder);
AuthenticationManager authenticationManager=authenticationManagerBuilder.build();
http.csrf().disable().authorizeHttpRequests()
.antMatchers("/**/login").permitAll()
.antMatchers("/**/signup").permitAll()
.antMatchers("/home/**").permitAll()
.anyRequest().authenticated().and()
.addFilter(getAuthenticationFilter(authenticationManager))
.addFilter(new AuthorizationFilter(authenticationManager))
.authenticationManager(authenticationManager)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
return http.build();
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么会这样。
authentication spring-security spring-boot api-authorization
我使用的是 Spring Boot 3,没有 WebSecurityConfigurationAdapter。以下为代码。但是 .authorizeRequests().antMatchers("/api/auth/**").permitAll(); 它给出错误。附屏幕截图。
我想允许“/api/auth/**”。
AuthorizeRequests() 似乎在 SpringBoot 3 中已弃用。有其他选择吗???
@EnableGlobalMethodSecurity(prePostEnabled=true) 似乎也已弃用。任何新的解决方案。

提前致谢。
package com.example.tokenAuth.security;
import com.example.tokenAuth.security.jwt.AuthEntryPointJwt;
import com.example.tokenAuth.security.jwt.AuthTokenFilter;
import com.example.tokenAuth.security.services.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig
{
@Autowired
UserDetailsServiceImpl userDetailsService;
@Autowired
private AuthEntryPointJwt unauthorizedHandler;
@Bean
public AuthTokenFilter authenticationJwtTokenFilter()
{
return new AuthTokenFilter();
}
@Bean …Run Code Online (Sandbox Code Playgroud) spring-security ×10
spring-boot ×8
spring ×4
java ×3
spring-mvc ×2
thymeleaf ×2
bootstrap-4 ×1
h2 ×1
jwt ×1
oauth-2.0 ×1
okta ×1
swagger-ui ×1
vaadin ×1