2017-08-13 138 views
0

我有一個簡單的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'); 
    } 
} 

當我發送請求時,在後臺日志中我看到,頁面沒有找到。但我不知道什麼是正確的網址。

+0

你讀過此頁:https://angular.io/guide/http和https://angular.io/tutorial/toh-pt6#providing-http-services。學習時他們是一個很好的資源 – Vega

+0

我讀了這個頁面,但我仍然不知道這是怎麼做的。 –

+0

到目前爲止你寫過什麼嗎?如果這樣向我們展示! – Vega

回答

0

如果你只是想了解它是如何做,然後看看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()); },這樣您就可以在每個請求中獲取已解析的數據。

+0

感謝您的回答。 –

+0

World of Angular還很年輕,所以不要害怕嘗試新事物,你可以看看[awesome-angular](https://github.com/AngularClass/awesome-angular) - set –

+0

我知道如何在Angular 2中構建簡單的應用程序並使用REST API但是我遇到了身份驗證問題您知道在哪裏可以看到使用Java REST API進行用戶身份驗證的工作示例嗎? –

0

所以我消費我使用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