gpt4 book ai didi

java - 一个应用程序中 Spring-Security 配置中的安全 Web 客户端和 API

转载 作者:行者123 更新时间:2023-12-01 21:17:39 27 4
gpt4 key购买 nike

我已经设置了一个在 tomcat 中运行的 Spring boot 应用程序,以 WAR 的形式分发到服务器

我有几个 HTML 页面确实可以使用表单安全性,但我也尝试添加 API,因此我切换到 JWT。

我的努力是将本地客户端与后端 API 结合在一个 WAR 文件中,因为我碰巧知道 Spring Security 可以实现这一点

编辑:我的 gradle

plugins {
id 'org.springframework.boot' version '2.2.1.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
id 'war'
}
....
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'com.auth0:java-jwt:3.8.3'

在我的 SecurityConfiguration.java 中我有

@Override
protected void configure(HttpSecurity http) throws Exception {
http
// remove csrf and state in session because in jwt we do not need them
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
// add jwt filters (1. authentication, 2. authorization)
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
.addFilter(new JwtAuthorizationFilter(authenticationManager(), this.userRepository))
.authorizeRequests()
// configure access rules
.antMatchers("/index.html").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers(HttpMethod.POST, "/login").permitAll()
.antMatchers("/api/public/management/*").hasRole("MANAGER")
.antMatchers("/api/public/admin/*").hasRole("ADMIN")
.anyRequest().authenticated();
}

编辑:添加了 JwtAuthenticationFilter

public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;

JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}

/* Trigger when we issue POST request to /login
We also need to pass in {"username":"admin", "password":"password"} in the request body
*/
@Override
public Authentication attemptAuthentication(
HttpServletRequest request,
HttpServletResponse response
) throws AuthenticationException {

// Grab credentials and map them to LoginViewModel
LoginViewModel credentials = null;
try {
credentials = new ObjectMapper().readValue(request.getInputStream(), LoginViewModel.class);
} catch (IOException e) {
e.printStackTrace();
}
// Create login token
assert credentials != null;
System.out.println("Credentials : " + credentials.getUsername() + ":" + credentials.getPassword());
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
credentials.getUsername(),
credentials.getPassword(),
new ArrayList<>()
);

// Authenticate user

return authenticationManager.authenticate(authenticationToken);
}

@Override
protected void successfulAuthentication(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain,
Authentication authResult
) {
// Grab principal
UserPrincipal principal = (UserPrincipal) authResult.getPrincipal();

// Create JWT Token
String token = JWT.create()
.withSubject(principal.getUsername())
.withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.sign(HMAC512(SECRET.getBytes()));
System.out.println("Token : " + TOKEN_PREFIX + token);
// Add token in response
response.addHeader(HEADER_STRING, TOKEN_PREFIX + token);
}
}

编辑:添加了 JwtAuthorizationFilter

public class JwtAuthorizationFilter extends BasicAuthenticationFilter {
private UserRepository userRepository;

JwtAuthorizationFilter(AuthenticationManager authenticationManager, UserRepository userRepository) {
super(authenticationManager);
this.userRepository = userRepository;
}

@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain
) throws IOException, ServletException {
// Read the Authorization header, where the JWT token should be
String header = request.getHeader(HEADER_STRING);

// If header does not contain BEARER or is null delegate to Spring impl and exit
if (header == null || !header.startsWith(TOKEN_PREFIX)) {
chain.doFilter(request, response);
return;
}

// If header is present, try grab user principal from database and perform authorization
Authentication authentication = getUsernamePasswordAuthentication(request);
SecurityContextHolder.getContext().setAuthentication(authentication);

// Continue filter execution
chain.doFilter(request, response);
}

private Authentication getUsernamePasswordAuthentication(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING)
.replace(TOKEN_PREFIX, "");

// parse the token and validate it
String userName = JWT.require(HMAC512(SECRET.getBytes()))
.build()
.verify(token)
.getSubject();

// Search in the DB if we find the user by token subject (username)
// If so, then grab user details and create spring auth token using username, pass, authorities/roles
if (userName != null) {
System.out.println("userName :" + userName);
User user = userRepository.findByUsername(userName);
UserPrincipal principal = new UserPrincipal(user);
return new UsernamePasswordAuthenticationToken(userName, null, principal.getAuthorities());
}
return null;
}

通常我可以通过运行 https://localhost:8443/index 从浏览器执行index.html它确实给了我一个错误

There was an unexpected error (type=Forbidden, status=403). Access Denied

但是,如果我在 Postman 中使用不记名 token 测试它,它会提供页面服务

我的问题是如何从 JwtAuthenticationFilter 中排除 HTML 内容以及如何实际授权我的 HTML 内容?

我的想法是将 formLogin() 与 JWT 结合起来,但我找不到示例代码来教我。

如果需要,请询问任何其他代码部分

最佳答案

很难确切地说出这么多自定义代码到底发生了什么,但这里有一些基于您的解释的提示。

可能性#1

首先,您的 JwtAuthenticationFilterJwtAuthorizationFilter 可能期望过高。当请求中没有承载 token 时,他们是否会尝试身份验证并授权请求?

简化此操作的一个好方法是升级到 Spring Security 5.1+ 并使用 its bearer token support :

http
.authorizeRequests()
.antMatchers("/index.html").permitAll()
... // other matchers
.anyRequest().authenticated()
.and()
.oauth2ResourceServer()
.jwt();

它仅在存在不记名 token 时激活。此外,它还会为您禁用包含不记名 token 的请求的 CSRF。

您可以添加formLogin(),但它与sessionCreationPolicy(STATELESS)有点不一致。表单登录需要 session 式 Web 应用程序。如果您想要一个在每个请求上发送其凭据的用户名/密码客户端,那么您需要 httpBasic() ,您可以这样做:

http
.authorizeRequests()
.antMatchers("/index.html").permitAll()
... // other matchers
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.oauth2ResourceServer()
.jwt();

通过此设置,httpBasic 仅在使用 Authorization: Basic 时才参与,oauth2ResourceServer 仅在使用 Authorization: Bearer 时参与.

如果您确实需要 formLogin(用户可以在其中填写 HTML 表单的 UI),那么您不希望应用程序是无状态的。你可以这样做:

http
.authorizeRequests()
.antMatchers("/index.html").permitAll()
... // other matchers
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.oauth2ResourceServer()
.jwt();

可能性#2

或者,其次,您可能会说 API 的 URI 与客户端应用程序完全分开。

例如,您的客户端应用程序的 URI 均以 /app 开头。API 的 URI 均以 /api 开头。

如果是这种情况,那么您可以创建两个 WebSecurityConfigurerAdapter 实例:

@Configuration
@Order(100)
public class AppConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) {
http
.requestMatchers()
.antMatchers("/app/**")
.and()
.authorizeRequests()
.antMatchers("/app/index.html").permitAll()
.anyRequest().authenticated()
.and()
.formLogin();
}
}

@Configuration
@Order(101)
public class ApiConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) {
http
.requestMatchers()
.antMatchers("/api/**")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(STATELESS)
.and()
.addFilter(new JwtAuthenticationFilter(...))
.addFilter(new JwtAuthorizationFilter(...))
.csrf().disable();
}
}

请注意,这两种设置都承认您不想为整个应用程序禁用 CSRF。您希望为客户端应用程序启用这种保护。

关于java - 一个应用程序中 Spring-Security 配置中的安全 Web 客户端和 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58861367/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com