我正在按照本教程学习基于角色的身份验证
我收到未经授权的错误
但在后端我没有收到该请求,添加为断点
@GetMapping("api/user/login")
public ResponseEntity<?> login(Principal principal)
{
if (principal == null)
{
return ResponseEntity.ok(principal);
}
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) principal;
User user = userService.findByUsername(token.getName());
user.setToken(jwtTokenProvider.generateToken(token));
return new ResponseEntity<>(user, HttpStatus.OK);
前端请求应该进入控制器,但似乎我在没有进入控制器的情况下得到响应。
任何人都可以帮助解决可能的原因。
配置方法
@Override
protected void configure(HttpSecurity http)
throws Exception
{
// Cross-origin-resource-sharing
http.cors().and().authorizeRequests()
// These are public pages.
.antMatchers("/resources/**", "/error", "/api/user/**").permitAll()
// These can be reachable for just have admin role.
.antMatchers("/api/admin/**").hasRole("ADMIN")
// all remaining paths should need authentication.
.anyRequest().fullyAuthenticated().and()
// logout will log the user out by invalidate session.
.logout().permitAll()
.logoutRequestMatcher(new AntPathRequestMatcher("/api/user/logout", "POST")).and()
// login form and path
.formLogin().loginPage("/api/user/login").and()
// enable basic authentication. Http header: basis username:password
.httpBasic().and()
// Cross side request forgery.
.csrf().disable();
}
import { NgModule } from '@angular/core';
import { Router,Routes, RouterModule } from '@angular/router';
import { EmployeeComponent } from './employee/employee.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { MainComponent } from './main/main.component';
import { FormExampleComponent } from './form-example/form-example.component';
import { MaterialButtonsComponent } from './material-buttons/material-buttons.component';
import { MatButtonToggleComponent } from './mat-button-toggle/mat-button-toggle.component';
import { LoginComponent } from './login/login.component';
import { RegistrationComponent } from './registration/registration.component';
import { DisplaySectionComponent } from './display-section/display-section.component';
import { MaterialIconComponent } from './material-icon/material-icon.component';
import { MaterialBadgesComponent } from './material-badges/material-badges.component';
import { MatSpinnerComponent } from './mat-spinner/mat-spinner.component';
import { MaterialToolbarComponent } from './material-toolbar/material-toolbar.component';
import { MaterialSidenavComponent } from './material-sidenav/material-sidenav.component';
import { MaterialMenuComponent } from './material-menu/material-menu.component';
import { MaterialListComponent } from './material-list/material-list.component';
import { MaterialGridListComponent } from './material-grid-list/material-grid-list.component';
import { MaterialExpansionPanelComponent } from './material-expansion-panel/material-expansion-panel.component';
import { MaterialCardsComponent } from './material-cards/material-cards.component';
import { MaterialTabsComponent } from './material-tabs/material-tabs.component';
import { MaterialSteppersComponent } from './material-steppers/material-steppers.component';
import { MaterialInputComponent } from './material-input/material-input.component';
import { MaterialSelectComponent } from './material-select/material-select.component';
import { MaterialAutocompleteComponent } from './material-autocomplete/material-autocomplete.component';
import { ShoppingCartComponent } from './shopping-cart/shopping-cart.component';
import { OrderDetailsComponent } from './order-details/order-details.component';
import { ProfileComponent } from './profile/profile.component';
import { DetailComponent } from './detail/detail.component';
import { AdminComponent } from './admin/admin.component';
import { UnauthorisedComponent } from './unauthorised/unauthorised.component';
import {AuthGuard} from './guard/auth.guard';
import {Role} from './model/role';
import { SecurityComponent } from './security/security.component';
const routes: Routes = [
{path:'security',component:SecurityComponent},
{path:'main',component:MainComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'employees',component:EmployeeComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'profile',component:ProfileComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'detail/:id',component:DetailComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'admin',component:AdminComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path : 'display', component:DisplaySectionComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path: '', redirectTo:'signin',pathMatch:'full'},
{path: 'formexample',component:FormExampleComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'matbutton',component:MaterialButtonsComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'matbuttontoggle',component:MatButtonToggleComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'signup',component:RegistrationComponent},
{path:'signin',component:LoginComponent},
{path:'icon',component:MaterialIconComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'badge',component:MaterialBadgesComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'spinner',component:MatSpinnerComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'badge',component:MaterialBadgesComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'toolbar',component:MaterialToolbarComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'sidenav',component:MaterialSidenavComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'menu',component:MaterialMenuComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'list',component:MaterialListComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'gridlist',component:MaterialGridListComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'expansionlist',component:MaterialExpansionPanelComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'cards',component:MaterialCardsComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'tabs',component:MaterialTabsComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'stepper',component:MaterialSteppersComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'input',component:MaterialInputComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'select',component:MaterialSelectComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'autocomplete',component:MaterialAutocompleteComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'shopping',component:ShoppingCartComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path:'shopping/order',component:OrderDetailsComponent,canActivate:[AuthGuard],data:{roles:[Role.ADMIN,Role.USER]}},
{path : '404', component:PageNotFoundComponent},
{path : '401', component:UnauthorisedComponent},
{path : '**', component:PageNotFoundComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes,{ enableTracing: true } )],
exports: [RouterModule]
})
export class AppRoutingModule {
constructor(private router : Router){
this.router.errorHandler = (error:any)=>{
this.router.navigate(['/404']);
}
}
}
登录时点击 onLogin(user: any){ console.log("this.user"+this.user);
this.userService.login(this.user).subscribe(data=>{
console.log("data"+data);
this.router.navigate(['/main']);
},err=>{
this.errorMessage = "username or password is incorrect";
});
}
用户服务
login(user: User): Observable<any> {
console.log("user.username "+user.username );
const headers = new HttpHeaders(user ? {
authorization: 'Basic '+btoa( user.username + ':' + user.password)
}:{});
return this.http.get<any> (API_URL + "login", {headers:headers}).pipe(
map(response => {
console.log("map"+response);
if(response) {
localStorage.setItem('currentUser', JSON.stringify(response));
this.currentUserSubject.next(response);
}
return response;
})
);
}