一个应用程序中Spring-Security配置中的安全Web-Client和API



我已经设置了一个在tomcat中运行的Spring引导应用程序,将其作为WAR分发到服务器

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

然后,我的努力是将本地客户端和后端API合并到一个WAR文件中,因为我碰巧知道这是可以使用SpringSecurity的

编辑:我的等级

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它确实给了我一个错误

出现意外错误(类型=Forbidden,状态=403(。通道拒绝

如果我用Bearer令牌在Postman中测试它,它会为页面服务

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

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

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

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

可能性#1

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

简化这一过程的一个好方法是升级到SpringSecurity5.1+并使用其承载令牌支持:

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

只有当存在承载令牌时,它才会激活。此外,对于包含承载令牌的请求,它会为您禁用CSRF。

您可以添加formLogin(),但它与sessionCreationPolicy(STATELESS)有点不一致。表单登录需要一个会话式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。您希望为客户端应用程序启用该保护。

经过调查,我找到了答案感谢@jzheaux的输入,它有助于澄清我需要做什么。

我需要将API从WebClient中分离出来,并在API部分使用JWT,但在WebClient部分使用FormLogin。

将两者结合起来可能是可能的,但我的编码经验还没有

最新更新