如何解决错误 GET http://localhost:8484/ 401
how to resolve the error GET http://localhost:8484/ 401
我正在使用 angular、spring 安全和 spring 引导编写登录页面。
问题是当我点击登录按钮时出现以下错误:
但是我确实在我的后端部分放置了 crossorgine,如您所见:
package com.app.habilitation.controller;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
@CrossOrigin(origins = "*")
public class UserController {
@GetMapping("/")
public String login() {
return "authenticaated succesfully";
}
@GetMapping("/getUsers")
public String getUsers() {
return "users";
}
}
这是我的 "usercontroller" 管理身份验证的控制器:
package com.app.habilitation.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure (HttpSecurity http) throws Exception {
http.cors();
http.csrf().disable();
http.authorizeRequests().antMatchers("/**").
fullyAuthenticated().and().httpBasic();
}
@Override
protected void configure (AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("hr")
.password("{noop}hr").roles("USER");
}
}
这是我在 angular 中的路由:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './components/login/login.component';
import { ForgotPasswordComponent } from './components/forgot-password/forgot-password.component';
import { InscriptionComponent } from './components/inscription/inscription.component';
import { HomeAdminComponent } from './components/home-admin/home-admin.component';
const routes: Routes = [
{path:'', redirectTo:"login", pathMatch:"full"},
{path: "forgot", component: ForgotPasswordComponent},
{path: 'login', component: LoginComponent},
{path: 'inscription', component: InscriptionComponent},
{path:'home-admin', component: HomeAdminComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
这是我的模块:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MatSliderModule } from '@angular/material/slider';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { LoginComponent } from './components/login/login.component';
import { MatCardModule } from '@angular/material/card';
import { MDBBootstrapModule } from 'angular-bootstrap-md';
import {MatTabsModule} from '@angular/material/tabs';
import { MatFormFieldModule} from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { FormsModule } from '@angular/forms';
import {MatInputModule} from '@angular/material/input';
import {MatButtonModule} from '@angular/material/button';
import { ForgotPasswordComponent } from './components/forgot-password/forgot-password.component';
import { InscriptionComponent } from './components/inscription/inscription.component';
import { RestapiService } from './restapi.service';
import { HttpClientModule } from '@angular/common/http';
import { HomeAdminComponent } from './components/home-admin/home-admin.component';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
ForgotPasswordComponent,
InscriptionComponent,
HomeAdminComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatSliderModule,
MDBBootstrapModule.forRoot(),
MatCardModule,
MatTabsModule,
MatFormFieldModule,
MatIconModule,
MatCheckboxModule,
MatInputModule,
MatButtonModule,
HttpClientModule,
FormsModule
],
providers: [RestapiService],
bootstrap: [AppComponent]
})
export class AppModule { }
这是我的服务:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class RestapiService {
constructor(private http:HttpClient) { }
public login(username:string, password:string) {
const headers = new HttpHeaders({Authorization: 'Basic' + btoa(username+":"+password)})
return this.http.get("http://localhost:8484/", {headers, responseType:'text' as 'json'});
}
public getUsers() {
let username="hr";
let password="hr";
const headers = new HttpHeaders({Authorization: 'Basic' + btoa(username+":"+password)});
return this.http.get("http://localhost:8484/getUsers", {headers});
}
}
这是我的 login.ts 页面:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { RestapiService } from 'src/app/restapi.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
username:string;
password:string;
message:any
constructor(private route: ActivatedRoute, private service:RestapiService, private router:Router) { }
ngOnInit(): void {
}
doLogin() {
let resp = this.service.login(this.username, this.password);
resp.subscribe(data=> {
this.message =data;
this.router.navigate(["home-admin"])
})
}
}
这是我的 login.html 页面:
<div class="cnx">
<!-- Default form login -->
<form class="text-center border border-light p-5">
<p class="h4 mb-4">Authentification</p>
<!-- Email -->
<input type="text" id="defaultLoginFormEmail" class="form-control mb-4" placeholder="Login" name="login" [(ngModel)]="username">
<!-- Password -->
<input type="password" id="defaultLoginFormPassword" class="form-control mb-4" placeholder="Password" name="password" [(ngModel)]="password">
<div class="d-flex justify-content-around">
<div>
<!-- Forgot password -->
<a routerLink="/forgot">Mot de passe oublié ?</a>
</div>
</div>
<!-- Sign in button -->
<button mdbBtn color="info" block="true" class="my-4" type="submit" id="btn-authentification" (click)="doLogin()">Se connecter</button>
<!-- Register -->
<p>Tu n'es pas un membre ?
<a routerLink= "/inscription">Enregistre toi</a>
</p>
</form>
<!-- Default form login -->
</div>
(我的 spring 引导服务器在端口 8484 中是 运行 因为我在我的 application.properties 文件中更改了它,如您在此处看到的那样):
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=nawfel
spring.datasource.password=hr
server.port=8484
有人可以帮我吗?
这是一个 401 未经授权的错误。它与 CORS 没有任何关系。您似乎在 'Basic'
字符串文字后缺少 space 。尝试以下
const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username + ":" + password)})
请注意 Basic
.
后空 space
我正在使用 angular、spring 安全和 spring 引导编写登录页面。 问题是当我点击登录按钮时出现以下错误:
但是我确实在我的后端部分放置了 crossorgine,如您所见:
package com.app.habilitation.controller;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
@CrossOrigin(origins = "*")
public class UserController {
@GetMapping("/")
public String login() {
return "authenticaated succesfully";
}
@GetMapping("/getUsers")
public String getUsers() {
return "users";
}
}
这是我的 "usercontroller" 管理身份验证的控制器:
package com.app.habilitation.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure (HttpSecurity http) throws Exception {
http.cors();
http.csrf().disable();
http.authorizeRequests().antMatchers("/**").
fullyAuthenticated().and().httpBasic();
}
@Override
protected void configure (AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("hr")
.password("{noop}hr").roles("USER");
}
}
这是我在 angular 中的路由:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './components/login/login.component';
import { ForgotPasswordComponent } from './components/forgot-password/forgot-password.component';
import { InscriptionComponent } from './components/inscription/inscription.component';
import { HomeAdminComponent } from './components/home-admin/home-admin.component';
const routes: Routes = [
{path:'', redirectTo:"login", pathMatch:"full"},
{path: "forgot", component: ForgotPasswordComponent},
{path: 'login', component: LoginComponent},
{path: 'inscription', component: InscriptionComponent},
{path:'home-admin', component: HomeAdminComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
这是我的模块:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MatSliderModule } from '@angular/material/slider';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { LoginComponent } from './components/login/login.component';
import { MatCardModule } from '@angular/material/card';
import { MDBBootstrapModule } from 'angular-bootstrap-md';
import {MatTabsModule} from '@angular/material/tabs';
import { MatFormFieldModule} from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { FormsModule } from '@angular/forms';
import {MatInputModule} from '@angular/material/input';
import {MatButtonModule} from '@angular/material/button';
import { ForgotPasswordComponent } from './components/forgot-password/forgot-password.component';
import { InscriptionComponent } from './components/inscription/inscription.component';
import { RestapiService } from './restapi.service';
import { HttpClientModule } from '@angular/common/http';
import { HomeAdminComponent } from './components/home-admin/home-admin.component';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
ForgotPasswordComponent,
InscriptionComponent,
HomeAdminComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatSliderModule,
MDBBootstrapModule.forRoot(),
MatCardModule,
MatTabsModule,
MatFormFieldModule,
MatIconModule,
MatCheckboxModule,
MatInputModule,
MatButtonModule,
HttpClientModule,
FormsModule
],
providers: [RestapiService],
bootstrap: [AppComponent]
})
export class AppModule { }
这是我的服务:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class RestapiService {
constructor(private http:HttpClient) { }
public login(username:string, password:string) {
const headers = new HttpHeaders({Authorization: 'Basic' + btoa(username+":"+password)})
return this.http.get("http://localhost:8484/", {headers, responseType:'text' as 'json'});
}
public getUsers() {
let username="hr";
let password="hr";
const headers = new HttpHeaders({Authorization: 'Basic' + btoa(username+":"+password)});
return this.http.get("http://localhost:8484/getUsers", {headers});
}
}
这是我的 login.ts 页面:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { RestapiService } from 'src/app/restapi.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
username:string;
password:string;
message:any
constructor(private route: ActivatedRoute, private service:RestapiService, private router:Router) { }
ngOnInit(): void {
}
doLogin() {
let resp = this.service.login(this.username, this.password);
resp.subscribe(data=> {
this.message =data;
this.router.navigate(["home-admin"])
})
}
}
这是我的 login.html 页面:
<div class="cnx">
<!-- Default form login -->
<form class="text-center border border-light p-5">
<p class="h4 mb-4">Authentification</p>
<!-- Email -->
<input type="text" id="defaultLoginFormEmail" class="form-control mb-4" placeholder="Login" name="login" [(ngModel)]="username">
<!-- Password -->
<input type="password" id="defaultLoginFormPassword" class="form-control mb-4" placeholder="Password" name="password" [(ngModel)]="password">
<div class="d-flex justify-content-around">
<div>
<!-- Forgot password -->
<a routerLink="/forgot">Mot de passe oublié ?</a>
</div>
</div>
<!-- Sign in button -->
<button mdbBtn color="info" block="true" class="my-4" type="submit" id="btn-authentification" (click)="doLogin()">Se connecter</button>
<!-- Register -->
<p>Tu n'es pas un membre ?
<a routerLink= "/inscription">Enregistre toi</a>
</p>
</form>
<!-- Default form login -->
</div>
(我的 spring 引导服务器在端口 8484 中是 运行 因为我在我的 application.properties 文件中更改了它,如您在此处看到的那样):
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=nawfel
spring.datasource.password=hr
server.port=8484
有人可以帮我吗?
这是一个 401 未经授权的错误。它与 CORS 没有任何关系。您似乎在 'Basic'
字符串文字后缺少 space 。尝试以下
const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username + ":" + password)})
请注意 Basic
.