角2和令牌认证
我有一个简单的Java REST API。我通过邮差测试这个API,并且一切正常。但是现在我想用这个API学习Angular2。我尝试登录到应用程序,我有问题,因为我不知道如何在Angular2中创建请求。在邮差我这样做。角2和令牌认证
Postman screen shot 这是我的代码,后端配置。
package org.mroczek.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter{
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("my-trusted-client")
.authorizedGrantTypes("client_credentials", "password")
.authorities("ROLE_CLIENT","ROLE_TRUSTED_CLIENT").scopes("read","write","trust")
.resourceIds("oauth2-resource").accessTokenValiditySeconds(5000).secret("secret");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
}
这是我autentication.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import 'rxjs/add/operator/map'
import {map} from 'rxjs/operator/map';
@Injectable()
export class AuthenticationService {
constructor(private http: Http) { }
login(username: string, password: string) {
var headers = new Headers();
headers.append('Content-Type', 'application/json;charset=UTF-8');
let body = JSON.stringify({ username: username, password: password });
return this.http.post('http://localhost:8080/',JSON.stringify({username, password }),{headers})
.map((response: Response) => {
console.log(response)
// login successful if there's a jwt token in the response
let user = response.json();
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
console.log(user);
return user;
});
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
}
}
当我发送请求时,在后台日志中我看到,页面没有找到。但我不知道什么是正确的网址。
如果你只是想了解它是如何做,然后看看Angular's Http documentation。 用法示例可能会这样看(未测试,我不使用这个API的话):
@Injectable()
export class SomeService {
constructor(protected http: Http) {}
public login() {
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Methods', 'POST');
headers.append('Access-Control-Allow-Credentials', 'true');
headers.append('Accept', 'application/json');
headers.append('Content-type', 'application/json');
let body = {}; // request's body here... (in general password shouldn't be passed as a query parameter, so you will probably like to place it here
return http.post('http://localhost:8080/oath/token?grant_type=password&username=user', JSON.stringify(body), {headers});
}
}
希望工程......祝你好运与管理这样的代码数百端点...
如果你想为你的应用提供了良好的解决方案,那么我会建议像库 ng2-http。它成功地提取了整个Http层 - 迄今为止,在我的项目中没有使用单个解决方法。当使用它,你不需要手动创建每个请求,每次等解析响应... 用法示例:为v0.0.3
// ./providers/rest/localhost.api.ts
@Injectable()
@BaseUrl('http://localhost:8080')
@DefaultHeaders({
'Accept': 'application/json',
'Content-Type': 'application/json'
})
export class LocalhostApi extends RESTClient {
@POST('oath/token')
public postOathToken(
@Query('grant_type') grantType: string,
@Query('username') userName: string,
@Query('password') password: string
@Body body: PostOathTokenBody
) {
return undefined;
}
}
// ./providers/rest/types.ts
// for this example let's say you want to send the exact same data as you received
export interface PostOathTokenBody {
access_token: string;
token_type: string;
expires_in: number;
scope: string;
}
// ./services/some.service.ts
@Injectable()
export class SomeService {
constructor(protected localhostApi: LocalhostApi) {}
public login(body: PostOathTokenBody) {
// and that's it, every time you want to use the endpoint, just do:
return this.localHostApi.postOathToken('username', 'user', 'password', {});
}
}
而且我定义了一些额外的AbstractApi
类,其他的API将延长,并添加:responseInterceptor(res) { return res.map(r => r.json()); }
,这样您就可以在每个请求中获取已解析的数据。
感谢您的回答。 –
World of Angular还很年轻,所以不要害怕尝试新事物,你可以看看[awesome-angular](https://github.com/AngularClass/awesome-angular) - set –
我知道如何在Angular 2中构建简单的应用程序并使用REST API但是我遇到了身份验证问题您知道在哪里可以看到使用Java REST API进行用户身份验证的工作示例吗? –
所以我消费我使用API Vue.JS和axios
login(){
var params = new URLSearchParams();
params.append('grant_type', 'password');
params.append('username', this.username);
params.append('password',this.password);
axios({
method:'post',
url:'oauth/token',
auth:{username:'my-trusted-client',password:'secret'},
headers: {"Content-type": "application/x-www-form-urlencoded; charset=utf-8"},
data:params
}).then(function(response){
set_cookie("access_token",response.data.access_token);
document.location.replace("/");
});
}
以上是代码,该代码工作正常。但我仍然认为如何正确地做,在角2
在角2我尝试这样做。
login(username, password): Observable<Response> {
const headers = new Headers({'Content-type': 'application/x-www-form-urlencoded; charset=utf-8'});
headers.append('Authorization', 'Basic bXktdHJ1c3RlZC1jbGllbnQ6c2VjcmV0');
headers.append('grant_type', 'password');
const options = new RequestOptions({headers: headers});
const body = JSON.stringify({username: username, password: password});
return this.http.post('http://localhost:8080/oauth/token', body, options)
.catch(this.handleError);
}
但我有这个错误。
XMLHttpRequest cannot load http://localhost:8080/oauth/token. Response for preflight has invalid HTTP status code 401
你读过此页:https://angular.io/guide/http和https://angular.io/tutorial/toh-pt6#providing-http-services。学习时他们是一个很好的资源 – Vega
我读了这个页面,但我仍然不知道这是怎么做的。 –
到目前为止你写过什么吗?如果这样向我们展示! – Vega