我正在使用API网关实现微服务。我想使用使用json-web-token的安全性。我使用angular-5作为前端,使用spring boot的后端微服务。我正在使用zuul进行API网关。请帮助解决我面临的问题。
登录后成功生成令牌。我在sessionStorage中保存令牌。这是authService.ts中的attemptAuth()方法
attemptAuth(ussername: string, password: string): Observable<any> {
const credentials = {username: ussername, password: password};
return this.http.post('http://localhost:6061/token/generate-token',credentials);
}
这是authService.ts中的getData()方法
getData():Observable<any>{
return this.http.get("http://localhost:6061/api/test");
}
以下是角度为5的拦截器.filename是app.interceptor.ts
import { Injectable } from '@angular/core';
import {HttpInterceptor, HttpRequest, HttpHandler, HttpSentEvent, HttpHeaderResponse, HttpProgressEvent,
HttpResponse, HttpUserEvent, HttpErrorResponse, HttpEvent,HttpHeaders} from '@angular/common/http';
import { Observable } from 'rxjs';
import { Router } from '@angular/router';
import {TokenStorage} from './token.storage';
const TOKEN_HEADER_KEY = 'Authorization';
@Injectable({providedIn:'root'})
export class Interceptor implements HttpInterceptor {
constructor(private token: TokenStorage, private router: Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
let authReq;
if (this.token.getToken() != null) {
let httpHeaders = new HttpHeaders();
httpHeaders = httpHeaders.set(TOKEN_HEADER_KEY, 'Bearer ' + this .token.getToken());
authReq = req.clone({headers:httpHeaders});
return next.handle(authReq);
}else{
return next.handle(req);
}
这是在端口6061上运行的api-gateway的安全性
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().
authorizeRequests()
.antMatchers("/token/*","/api/*").permitAll()
.anyRequest().authenticated() .and().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
在application.properties中定义的zuul属性。后端微服务正在端口8080上运行。
zuul.routes.resource.path=/api
zuul.routes.resource.url=http://localhost:8080
以下是API网关中的AuthenticationManager
@RestController
@CrossOrigin("*")
@RequestMapping("/token")
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private UserService userService;
@RequestMapping(value = "/generate-token", method = RequestMethod.POST)
public ResponseEntity<?> register(@RequestBody LoginUser loginUser) throws AuthenticationException {
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginUser.getUsername(),
loginUser.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
final User user = userService.findOne(loginUser.getUsername());
final String token = jwtTokenUtil.generateToken(user);
return ResponseEntity.ok(new AuthToken(token));
}
/* @RequestMapping(value = "/test", method = RequestMethod.GET)
public ResponseEntity<?> test(){
return ResponseEntity.ok("test");
}*/
}
这里我有目的地评论了测试方法。如果我取消注释此方法的网址&#39; http://localhost:6061/api/test&#39;会工作我不想要的。我希望将URL转发到我的API网关中没有发生的zuul映射服务。 请在我做错的地方给我解决方案。