令牌jwt与spring boot配合使用,但与angular配合使用时存在错误
当我尝试在spring boot中使用jwt时,它可以工作 [他创建了令牌][4] 我认为弹簧靴没有问题,我不知道它有什么问题 这是我的路线令牌jwt与spring boot配合使用,但与angular配合使用时存在错误,angular,spring-boot,authentication,spring-security,jwt-auth,Angular,Spring Boot,Authentication,Spring Security,Jwt Auth,当我尝试在spring boot中使用jwt时,它可以工作 [他创建了令牌][4] 我认为弹簧靴没有问题,我不知道它有什么问题 这是我的路线 import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { RegisterComponent } from './register/register.component'; import { L
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { RegisterComponent } from './register/register.component';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
import { BoardUserComponent } from './board-user/board-user.component';
import { BoardModeratorComponent } from './board-moderator/board-moderator.component';
import { BoardAdminComponent } from './board-admin/board-admin.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'profile', component: ProfileComponent },
{ path: 'user', component: BoardUserComponent },
{ path: 'mod', component: BoardModeratorComponent },
{ path: 'admin', component: BoardAdminComponent },
{ path: '', redirectTo: 'home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
这是我的身份验证服务
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
const AUTH_API = 'http://localhost:8080/api/auth/';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
login(credentials): Observable<any> {
return this.http.post(AUTH_API + 'signin', {
username: credentials.username,
password: credentials.password
}, httpOptions);
}
register(user): Observable<any> {
return this.http.post(AUTH_API + 'signup', {
username: user.username,
email: user.email,
password: user.password
}, httpOptions);
}
}
用户服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
const API_URL = 'http://localhost:8080/api/test/';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) { }
getPublicContent(): Observable<any> {
return this.http.get(API_URL + 'all', { responseType: 'text' });
}
getUserBoard(): Observable<any> {
return this.http.get(API_URL + 'user', { responseType: 'text' });
}
getModeratorBoard(): Observable<any> {
return this.http.get(API_URL + 'mod', { responseType: 'text' });
}
getAdminBoard(): Observable<any> {
return this.http.get(API_URL + 'admin', { responseType: 'text' });
}
}
你能不能也展示一下BoardUserComponent的js代码?我假设您检查用户是否登录到其中,并且您在某个地方输入了一个类型,因此在本例中不要这样做。你应该使用警卫。 制作一个这样的保护文件,检查用户是否登录,然后必须返回一个布尔值 user.guard.ts 之后,您可以将其导入路由文件中,并像这样写入路径
{
path: 'user',
canActivate: [UserGuard],
component: BoardUserComponent
},
如果您能向我们展示您的Angular路由代码和您拥有的任何身份验证服务,这将非常有用。我编辑了我的问题,因此请帮助我从“@Angular/core”导入{Component,OnInit};从“../\u service/user.service”导入{UserService}@组件{selector:'app board user',templateUrl:'./board user.Component.html',styleURL:['./board user.Component.css']}导出类BoardUserComponent实现OnInit{content=;constructorprivate userService:userService{}ngOnInit{this.userService.getUserBoard.subscribe data=>{this.content=data;},err=>{this.content=JSON.parseerr.error.message;};}}}我没有类似于isloggedin的方法我检查UserGuard和im重定向的解决方案['/auth/login]
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import {TokenStorageService} from '../auth/token-storage.service';
const TOKEN_HEADER_KEY = 'Authorization';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private token: TokenStorageService) { }
intercept(req: HttpRequest<any>, next: HttpHandler) {
let authReq = req;
const token = this.token.getToken();
if (token != null) {
authReq = req.clone({ headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token) });
}
return next.handle(authReq);
}
}
export const authInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
];
import { Component, OnInit } from '@angular/core';
import {AuthService} from '../auth/auth.service';
import {TokenStorageService} from '../auth/token-storage.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
form: any = {};
isLoggedIn = false;
isLoginFailed = false;
errorMessage = '';
roles: string[] = [];
constructor(private authService: AuthService, private tokenStorage: TokenStorageService) { }
ngOnInit() {
if (this.tokenStorage.getToken()) {
this.isLoggedIn = true;
this.roles = this.tokenStorage.getUser().roles;
}
}
onSubmit() {
this.authService.login(this.form).subscribe(
data => {
this.tokenStorage.saveToken(data.accessToken);
this.tokenStorage.saveUser(data);
this.isLoginFailed = false;
this.isLoggedIn = true;
this.roles = this.tokenStorage.getUser().roles;
this.reloadPage();
},
err => {
this.errorMessage = err.error.message;
this.isLoginFailed = true;
}
);
}
reloadPage() {
window.location.reload();
}
}
import { Injectable } from '@angular/core'
import { CanActivate, Router } from '@angular/router';
import { AuthService } from '@services/auth/auth.service';
@Injectable({
providedIn: 'root'
})
export class UserGuard implements CanActivate {
constructor(
private _AuthService: AuthService,
private _Router: Router
) {}
canActivate() {
if(this._AuthService.isLoggedIn()) {
return true;
} else {
this._Router.navigate(['/auth/login']);
return false;
}
}
}
{
path: 'user',
canActivate: [UserGuard],
component: BoardUserComponent
},