Skip to content

Commit

Permalink
fix: 修复SecurityAuthTokenFilter解析token报错导致获取token接口401错误
Browse files Browse the repository at this point in the history
  • Loading branch information
damingerdai committed Mar 1, 2024
1 parent cb48a0d commit 32f0d5c
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 44 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import org.daming.hoteler.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
Expand Down Expand Up @@ -65,15 +64,6 @@ protected void doFilterInternal(HttpServletRequest servletRequest, HttpServletRe
ThreadLocalContextHolder.put(context);
context.setIn(in);
context.setRequestId(UUID.randomUUID().toString());
// if (!isFilter(requestUrl)
// && !requestUrl.contains("token")
// && (!requestUrl.contains("/api/v1/job") || requestUrl.contains("/api/v1/job/jobinfos"))) {
// logger.info("verify url: " + requestUrl);
// // verifyHttpHeaders(request);
// verifyToken(request, context);
// } else {
// logger.info("url: " + requestUrl + " is ignored");
// }
verifyToken(context, request);
filterChain.doFilter(servletRequest, servletResponse);
} catch (ExpiredJwtException ex) {
Expand Down Expand Up @@ -144,11 +134,13 @@ private boolean isFilter(String url) {
private void verifyToken(HotelerContext context, HttpServletRequest httpRequest) {
final String requestTokenHeader = httpRequest.getHeader("Authorization");
if (Objects.isNull(requestTokenHeader) || !requestTokenHeader.startsWith("Bearer ")) {
throw ExceptionBuilder.buildException(600002, "访问拒绝.");
// throw ExceptionBuilder.buildException(600002, "访问拒绝.");
return;
}
var accessToken = requestTokenHeader.substring(7);
if (!StringUtils.hasText(accessToken)) {
throw ExceptionBuilder.buildException(600002, "访问拒绝.");
// throw ExceptionBuilder.buildException(600002, "访问拒绝.");
return;
}
context.setAccessToken(accessToken);
var key = JwtUtil.generalKey(this.secretPropService.getKey());
Expand All @@ -161,20 +153,23 @@ private void verifyToken(HotelerContext context, HttpServletRequest httpRequest)
}

private void verifyGrantedAuthority(User user) {
if (StringUtils.hasLength(user.getUsername()) && SecurityContextHolder.getContext().getAuthentication() == null) {
// 如果没过期,保持登录状态
// 将用户信息存入 authentication,方便后续校验
Set<GrantedAuthority> grantedAuthorities = user.getRoles()
.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName().trim().toUpperCase()))
.collect(Collectors.toSet());
var authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), null, grantedAuthorities);
// SecurityContextHolder 权限验证上下文
var securityContext = SecurityContextHolder.getContext();
// 指示用户已通过身份验证
securityContext.setAuthentication(authentication);

if (StringUtils.isEmpty(user.getUsername())) {
return;
}
if (Objects.nonNull(SecurityContextHolder.getContext().getAuthentication())) {
return;
}
// 如果没过期,保持登录状态
// 将用户信息存入 authentication,方便后续校验
Set<GrantedAuthority> grantedAuthorities = user.getRoles()
.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName().trim().toUpperCase()))
.collect(Collectors.toSet());
var authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), null, grantedAuthorities);
// SecurityContextHolder 权限验证上下文
var securityContext = SecurityContextHolder.getContext();
// 指示用户已通过身份验证
securityContext.setAuthentication(authentication);
}

public SecurityAuthTokenFilter(
Expand Down
25 changes: 13 additions & 12 deletions src/main/java/org/daming/hoteler/api/web/JobController.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,28 +48,31 @@ public String updateCrpytoCustomerId() {
return "pong";
}

@Operation(summary = "add ping job", security = { @SecurityRequirement(name = "bearer-key") })
@PostMapping("add-ping-task")
public String addPingTask(@RequestBody AddPingJobTaskRequest request) {
try {
var runDateTime = request.getRunDateTime();
var zoneId = ZoneOffset.systemDefault().getId();
var triggerName = "ping" + zoneId + runDateTime.toInstant(ZonedDateTime.now().getOffset());
var zoneId = ZoneOffset.systemDefault();
var localZonedDateTime = runDateTime.withZoneSameInstant(ZoneOffset.systemDefault());

var triggerName = "ping-" + zoneId + "-" + localZonedDateTime.toInstant();
var cron = CronBuilder.cron(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ))
.withSecond(FieldExpressionFactory.on(runDateTime.getSecond()))
.withMinute(FieldExpressionFactory.on(runDateTime.getMinute()))
.withHour(FieldExpressionFactory.on(runDateTime.getHour()))
.withDoM(FieldExpressionFactory.on(runDateTime.getDayOfMonth()))
.withMonth(FieldExpressionFactory.on(runDateTime.getMonth().getValue()))
.withSecond(FieldExpressionFactory.on(localZonedDateTime.getSecond()))
.withMinute(FieldExpressionFactory.on(localZonedDateTime.getMinute()))
.withHour(FieldExpressionFactory.on(localZonedDateTime.getHour()))
.withDoM(FieldExpressionFactory.on(localZonedDateTime.getDayOfMonth()))
.withMonth(FieldExpressionFactory.on(localZonedDateTime.getMonth().getValue()))
.withDoW(FieldExpression.questionMark())
.withYear(FieldExpressionFactory.on(runDateTime.getYear()))
.withYear(FieldExpressionFactory.on(localZonedDateTime.getYear()))
.instance();

var cronExpression = cron.asString();
LoggerManager.getCommonLogger().info("add ping job: trigger {} -> cron {}", triggerName, cronExpression);
this.quartzService.addJob(triggerName, "ping", cronExpression, PingJob.class);
return "success";
} catch (Exception ex) {
ex.printStackTrace();
return ex.getMessage();
throw this.errorService.createHotelerSystemException(ex.getMessage(), ex);
}

}
Expand All @@ -78,9 +81,7 @@ public String addPingTask(@RequestBody AddPingJobTaskRequest request) {
@GetMapping("jobinfos")
public ListResponse<JobInfo> listQuartzJobs() throws HotelerException {
try {
System.out.println("jobinfos");
var jobs = this.quartzService.listJob();
System.out.println(jobs);
return new ListResponse<>(jobs);
} catch (Exception ex) {
throw this.errorService.createHotelerSystemException(ex.getMessage(), ex);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ public SecurityFilterChain filterChain(
.requestMatchers("/**.js", "/**.css", "/**.ico", "/**.woff2", "/**.svg").anonymous()
.requestMatchers("/api/v1/token").anonymous()//普通用户权限
.requestMatchers("/api/v1/job/jobinfos").hasRole("USERS")//普通用户权限
.requestMatchers(HttpMethod.POST, "/api/v1/token").anonymous()
.requestMatchers("/api/login").permitAll()
.requestMatchers("/api/**").hasRole("USERS")//普通用户权限
.requestMatchers(authWhiteList).permitAll()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package org.daming.hoteler.pojo.request;

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.StringJoiner;

/**
Expand All @@ -9,17 +9,17 @@
*/
public class AddPingJobTaskRequest {

private LocalDateTime runDateTime;
private ZonedDateTime runDateTime;

public LocalDateTime getRunDateTime() {
public ZonedDateTime getRunDateTime() {
return runDateTime;
}

public void setRunDateTime(LocalDateTime runDateTime) {
public void setRunDateTime(ZonedDateTime runDateTime) {
this.runDateTime = runDateTime;
}

public AddPingJobTaskRequest(LocalDateTime runDateTime) {
public AddPingJobTaskRequest(ZonedDateTime runDateTime) {
super();
this.runDateTime = runDateTime;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public void addJob(String name, String group, String cron, String className) thr
public void addJob(String name, String group, String cron, Class<? extends Job> clazz) throws SchedulerException {
try {
TriggerKey triggerKey = TriggerKey.triggerKey(name, group);
JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(name, group).build();
JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(name, group).storeDurably().build();
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
scheduler.scheduleJob(jobDetail, trigger);
} catch (Exception e) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ secret:
key: damingerdai

logger:
level: debug
level: info

springdoc:
packagesToScan: org.daming.hoteler.api.web
Expand Down

0 comments on commit 32f0d5c

Please sign in to comment.