Java 我可以在没有用户的情况下为我的Spring Security应用程序生成JWT吗?
我想生成一个带有过期日期的JWT,以便人们无需注册和创建用户即可访问系统。这可能吗?我试过使用JwtTokenProvider,但它需要一个LoginRequest才能使用Jwts。builder还需要一个用户 如果您想使用spring安全性,可以创建安全配置并扩展WebSecurity配置适配器。然后重点是定制提供者 这是扩展genericFilterBean的筛选器类。在这个类中监视每个请求 您将检查它是否正确 我创建TokenTokenProvider类并依赖于JWTFilter,然后使用ValidToken方法 若令牌已发送且未验证,则引发异常 如果未发送令牌,则转到超级方法,以便流继续并在auth.authenticationProvider中工作。Spring知道在幕后启动customAuthenticationProvider,因为您设置了SecurityConfiguration类 您可以将此类用于创建令牌或验证令牌 您可以在create方法中定义令牌过期的过期日期Java 我可以在没有用户的情况下为我的Spring Security应用程序生成JWT吗?,java,spring,spring-security,jwt,Java,Spring,Spring Security,Jwt,我想生成一个带有过期日期的JWT,以便人们无需注册和创建用户即可访问系统。这可能吗?我试过使用JwtTokenProvider,但它需要一个LoginRequest才能使用Jwts。builder还需要一个用户 如果您想使用spring安全性,可以创建安全配置并扩展WebSecurity配置适配器。然后重点是定制提供者 这是扩展genericFilterBean的筛选器类。在这个类中监视每个请求 您将检查它是否正确 我创建TokenTokenProvider类并依赖于JWTFilter,然后使用
如果任何人都可以获得JWT,那么JWT的价值是什么?…从每个人都可以获得的端点移除安全性access@RobOhRob有一个用例的可能性,他将创建JWT令牌并与客户秘密共享。在他的情况下,他不想区分客户机,即用户。你可以在过滤器中实现这一点。其中filter检查头并读取授权头并将authenticated设置为true,authenticated设置为一个空的arrayList,并且您的所有端点不应该是hasRole,而应该使用.antMatchers/yourUrl/**.authenticated@Praveenkumarlasangi为什么不让他的客户登录呢?。。。。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
@Autowired
private JWTConfigurer securityConfigurerAdapter;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//you can write customAuth provider
auth.authenticationProvider(customAuthenticationProvider);
}
@Override
public void configure(WebSecurity web) throws Exception {
//Some ignore etc.
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.csrf()
.disable().and()
.headers()
.frameOptions()
.disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
//important here
.antMatchers("/api/v1/authentication/**").permitAll()
.anyRequest().authenticated()
.and()
.apply(securityConfigurerAdapter);
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return this.authenticationManager();
}
}
@Component
public class JWTFilter extends GenericFilterBean {
private final Logger log = LoggerFactory.getLogger(JWTFilter.class);
@Autowired
private TokenProvider tokenProvider;
@Autowired
private MessageSource msgSource;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
try {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
//Resolve method is optional what you want to use
String jwt = resolveToken(httpServletRequest);
if (StringUtils.hasText(jwt)) {
//token validation is important becouse of expires date into token
// and you will check expired date
if (this.tokenProvider.validateToken(jwt)) {
String jwtMd5 = DigestUtils.md5Hex(jwt);
MDC.put("jwt",jwtMd5);
Authentication authentication = this.tokenProvider.getAuthentication(jwt);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
filterChain.doFilter(servletRequest, servletResponse);
}catch(Exception ex){
handleException((HttpServletResponse) servletResponse,ex);
}
}
private String resolveToken(HttpServletRequest request) {
String bearerToken = request.getHeader(JWTConfigurer.AUTHENTICATION_HEADER);
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
String jwt = bearerToken.substring(7, bearerToken.length());
return jwt;
}
String jwt = request.getParameter(JWTConfigurer.AUTHENTICATION_TOKEN);
if (StringUtils.hasText(jwt)) {
return jwt;
}
return null;
}
}
@Component public class TokenProvider {
private final Logger log = LoggerFactory.getLogger(TokenProvider.class);
private static final String AUTHORITIES_KEY = "auth";
private static final String WTS_USER_ID = "wtsUserId";
private static final String CHANNEL_PERMISSIONS = "channelPermissions";
private static final String APP_ROLES = "appRoles";
private String secretKey;
private long tokenValidityInSeconds;
@Autowired private ApplicationProperties applicationProperties;
@PostConstruct public void init() {
this.tokenValidityInSeconds = 1000;
}
public String createToken(Authentication authentication, Boolean rememberMe) { List<String> authorities = authentication.getAuthorities().stream().map(authority -> authority.getAuthority())
.collect(Collectors.toList());
//Token creation format is this
// token will be three part important parts are claims and sign
// claims refers to body to use datas
// sign will use to validation
return Jwts.builder().setSubject(authentication.getName()).claim(AUTHORITIES_KEY, authorities)
.claim(WTS_USER_ID, ((JWTAuthentication) authentication).getWtsUserId())
.claim(CHANNEL_PERMISSIONS, ((JWTAuthentication) authentication).getChannelPermissions())
.claim(APP_ROLES, ((JWTAuthentication) authentication).getAppRoles())
.signWith(SignatureAlgorithm.HS512, secretKey).setExpiration(tokenValidityInSeconds).compact(); }
@SuppressWarnings("unchecked") public Authentication getAuthentication(String token) { Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
List<String> list = (List<String>) claims.get(AUTHORITIES_KEY); Collection<? extends GrantedAuthority> authorities = list.stream()
.map(authority -> new SimpleGrantedAuthority(authority)).collect(Collectors.toList()); Integer wtsUserId = (Integer) claims.get(WTS_USER_ID); List<String> appRoles = (List<String>) claims.get(APP_ROLES);
ObjectMapper objectMapper = new ObjectMapper(); List<ChannelPermission> channelPermissions = objectMapper.convertValue(claims.get(CHANNEL_PERMISSIONS),
new TypeReference<List<ChannelPermission>>() {
});
return new JWTAuthentication(token, wtsUserId, claims.getSubject(), authorities, channelPermissions, appRoles); }
public boolean validateToken(String authToken) {
try {
Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken);
return true;
} catch (SignatureException e) {
log.info("Invalid JWT signature: " + e.getMessage());
return false;
} } }
@RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ApiResponse login(@RequestBody @Validated AuthenticationRequestDTO authenticationRequest) {
Authentication authentication = this.authenticationManager.authenticate(new JWTAuthentication(
RandomUid, RandomPwd, "anonymous"));
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = tokenProvider.createToken(authentication, false);
return new ApiResponse(ApiResponseStatus.SUCCESS, new AuthenticationResponseDTO(token));
}