我希望在 spring security 中设置 ForwardedHeaderFilter ,这样我就可以让 spring 知道登录后要使用哪个协议。我在负载均衡器后面有几个应用程序服务器(使用 ssl 终止),并且 spring security 使用 http (而不是 https)重定向用户。因此,我的用户现在收到了一条烦人的警告消息。我可以在网上找到的唯一示例是使用 spring boot,但我没有实现。
我想在我的安全配置中使用“addFilterBefore()”方法,但从未调用过滤器。
有任何想法吗?
// Apply sameOrigin policy for iframe embeddings
http.headers().frameOptions().sameOrigin();
// ********* Add filter here? *******
http.addFilterBefore(new ForwardedHeaderFilter(), ChannelProcessingFilter.class);
// Authorization filters
http.authorizeRequests().antMatchers("/sysAdmin/**", "/monitoring/**").access("isFullyAuthenticated() and hasRole('GOD')");
http.authorizeRequests().antMatchers("/app/**").authenticated();
http.authorizeRequests().antMatchers("/**").permitAll();
http.formLogin()
.loginPage("/public/login.jsp")
.loginProcessingUrl("/login")
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/app/Dashboard.action", false)
.failureHandler(customAuthenticationFailureHandler());
// Disable so that logout "get" url works (otherwise you have to do a html form)
http.csrf().disable();
http.logout().logoutSuccessUrl("/public/login.jsp");
http.sessionManagement()
.invalidSessionUrl("/public/expiredSession.jsp?expiredId=2")
.maximumSessions(2)
.sessionRegistry(sessionRegistry())
.expiredUrl("/public/expiredSession.jsp?expiredId=3");
Run Code Online (Sandbox Code Playgroud) 我在我的角度应用程序中使用 oauth2 和 sso。我的其余后端验证每个请求发送的身份验证令牌。现在我想使用 oid 声明从我的数据库加载用户并将其保存在主体中。另外我想在“GrantedAuthorities”中添加用户权限。
食品服务
[...]
public Foo getFooByOid(String oid) throws FooNotFoundException {
return fooRepository.findByOid(oid)
.orElseThrow(() -> new FooNotFoundException("Foo with oid: " + oid + " not found"));
}
Run Code Online (Sandbox Code Playgroud)
安全配置
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests(auth -> auth
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> {
oauth2.jwt();
});
}
}
Run Code Online (Sandbox Code Playgroud)
spring.security.oauth2.resourceserver.jwt.jwk-set-uri 和 spring.security.oauth2.resourceserver.jwt.issuer-uri 在 application.properties 中定义
之后,我的主体包含所有声明、标头和令牌:
任何人都可以帮助我该怎么做吗?谢谢
是否可以在@PreAuthorize中使用请求标头值?
在我的应用程序中,所有请求都包含一个自定义标头,我需要将其与用户角色结合使用,以确定是否应允许它们访问控制器。
如果有人手动指定标头也没关系,因为这不会成为安全问题,因为最终角色将控制它。但我需要使用它来减少在每个控制器方法中手动检查的次数。
谢谢你,马特
spring spring-security spring-boot spring-expression-language
我想通过创建一个简单的登录屏幕在我的项目中使用 Spring Boot Security,但在运行应用程序时出现这些错误
描述:com.panchmeru_studio.controller.UserController 中构造函数的参数 1 需要类型为“org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder”的 bean,但无法找到。
操作:考虑在配置中定义 org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' 类型的 bean。 这是我的代码。
用户控制器
package com.panchmeru_studio.controller;
import com.panchmeru_studio.entities.ApplicationUser;
import com.panchmeru_studio.repository.ApplicationUserRepository;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
private ApplicationUserRepository applicationUserRepository;
private BCryptPasswordEncoder bCryptPasswordEncoder;
public UserController(ApplicationUserRepository applicationUserRepository,
BCryptPasswordEncoder bCryptPasswordEncoder) {
this.applicationUserRepository = applicationUserRepository;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@PostMapping("/record")
public void signUp(@RequestBody ApplicationUser applicationUser) {
applicationUser.setPassword(bCryptPasswordEncoder.encode(applicationUser.getPassword()));
applicationUserRepository.save(applicationUser);
}
}
Run Code Online (Sandbox Code Playgroud)
安全配置.java
package com.panchmeru_studio.security;
import com.panchmeru_studio.filter.AuthenticationFilter;
import com.panchmeru_studio.filter.AuthorizationFilter;
import com.panchmeru_studio.service.ApplicationUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; …Run Code Online (Sandbox Code Playgroud) java spring spring-security spring-boot spring-security-rest
如何获取过滤器以应用于根路径之外的每个请求(我想忽略的请求除外)?这是我的例子:
我有一个 Spring Security 过滤器,如下所示:
private static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.antMatcher("/**")
.addFilterBefore(new AuthenticationFilter(), basicAuthenticationFilter.class);
}
@Override
public void configure(WebSecurity web) {
web
.ignoring()
.requestMatchers(SecurityServletRequestMatchers.servletIgnoreAuthMatcher());
}
}
Run Code Online (Sandbox Code Playgroud)
该过滤器填充一个CustomApiToken包含所有标头信息的对象,并将其放入 Spring Security 上下文中SecurityContextHolder.getContext().setAuthentication(token),以便轻松访问请求控制器上的令牌。
我正在尝试将 Springfox 添加到项目中,这意味着我想禁用 UI 和 API 文档页面的过滤器。
我最初的尝试是在该方法中添加一个子句:
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.antMatcher("/**")
.addFilterBefore(new AuthenticationFilter(), BasicAuthenticationFilter.class);
http
.requestMatcher(SecurityServletRequestMatchers.servletIgnoreAuthMatcher())
.headers() //.servletIgnoreAuthMatchers has all the swagger urls also
.defaultsDisabled()
.disable() …Run Code Online (Sandbox Code Playgroud) 我要求实施 CSRF 来防止对 java 服务器应用程序的攻击。这是一个提供大量 Web REST API 服务的应用程序。\n我查看了许多指南并在堆栈上进行了搜索,但仍然有一些顾虑。\n我知道对于 GET 请求来说是不需要的。
\n所以,如果我错了,请纠正我。
\n这是我的过滤器。
\n public class ValidateCSRFToken implements Filter {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ValidateCSRFToken.class);\n\n @Override\n public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {\n HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;\n HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;\n // Spring put the CSRF token in session attribute "_csrf"\n CsrfToken csrfToken = (CsrfToken) httpServletRequest.getAttribute("_csrf");\n\n // Send the …Run Code Online (Sandbox Code Playgroud) 我正在开发一个实现 JWT 身份验证的 Spring Boot 项目,但我发现了一些困难。它基于 Udemy 课程中发现的一个示例,我正在尝试适应我的特定用例。它由以下两个微服务组成:
GET-USER-WS:这是从数据库获取用户信息的微服务。
AuthServerJWT:此微服务调用GET-USER-WS来获取用户信息并构建将由其他微服务使用的 JWT 令牌。
基本上,第二个AuthServerJWT包含以下JwtAuthenticationRestController控制器类:
@RestController
//@CrossOrigin(origins = "http://localhost:4200")
public class JwtAuthenticationRestController {
@Value("${sicurezza.header}")
private String tokenHeader;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
@Qualifier("customUserDetailsService")
private UserDetailsService userDetailsService;
private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationRestController.class);
@PostMapping(value = "${sicurezza.uri}")
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtTokenRequest authenticationRequest)
throws AuthenticationException {
logger.info("Autenticazione e Generazione Token");
authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails); …Run Code Online (Sandbox Code Playgroud) 控制器
@GetMapping("/api/data")
String response(){
}
Run Code Online (Sandbox Code Playgroud)
应用程序属性
server.servlet.context-path=/v1
Run Code Online (Sandbox Code Playgroud)
弹簧安全
http.authorizeRequests().anyMatcher("/v1/**").authenicated()
Run Code Online (Sandbox Code Playgroud)
这里没有发生身份验证。我相信, spring-security 忽略了application.properties 中配置的上下文路径。为什么 spring-security 忽略上下文路径。如何解决这个问题?
对于上图,我预计会出现 401,因为 v1/** 应该已获得授权
这工作正常,
http.authorizeRequests().anyMatcher("/**").authenicated()
Run Code Online (Sandbox Code Playgroud) 我正在尝试理解 Spring 授权服务器。
\n遵循各种教程和原始文档,几乎是配置依赖项 \xe2\x80\x93 后的第一步
\ndependencies {\n implementation 'org.springframework.boot:spring-boot-starter-webflux'\n implementation 'org.springframework.boot:spring-boot-starter-security'\n implementation 'org.springframework.security:spring-security-oauth2-authorization-server:0.2.1'\n// other db/test stuff\n}\nRun Code Online (Sandbox Code Playgroud)\n@EnableAuthorizationServer\xe2\x80\x93 是为主类添加注解。
除了我的 IDE (NetBeans) 没有从导入中得知它指的是什么。
\n那么:导入路径应该用于什么@EnableAuthorizationServer?(而且,从逻辑上讲,是否还需要一些其他依赖项才能识别它?)
我正在使用spring-security-oauth2来实现我的 OAuth2 授权服务器。spring-security-oauth2 即将消失,我知道我需要将其替换为spring-authorization-server
问题: 不同的客户端是否可以有不同的令牌到期时间(这里客户端代表客户端 ID/客户端秘密对)?
如果是,您能否分享文档/示例代码spring-authorization-server?
如果不是,这是 spring-authorization-server 的限制还是 OAuth2 规范不允许?
(澄清一下,我并不是说在 spring-security-oauth2 中这是可能的,如果是的话我也想知道)
spring-security ×10
spring ×7
java ×6
spring-boot ×6
jwt ×2
oauth-2.0 ×2
csrf ×1
csrf-token ×1
oauth ×1
principal ×1
springfox ×1