angular2-devise-token-auth is a helper library for working with Devise Token Auth in your Angular 2 applications.
npm install angular2-devise-token-auth --save
The library comes with some helpers that are useful in your Angular 2 apps.
AuthHttp
- a wrapper around Angular's Http
that allows for individual and explicit authenticated HTTP requestsAuthService
- provide the following features according the api:
sign in
sign up
sign out
validate token
Use AuthService
for your authentication workflows. After you signIn()
using AuthService
, use AuthHttp
throughout your application instead of Angular's Http
. All requests will be authorized through the headers that will be sent automatically.
You don't need to worry about it :sunglasses:.
It's supposed that you used Angular CLI to create your app.
Include Auth library in the vendor files
Open angular-cli-build.js
.
Include the library in the vendorNpmFiles array:
var Angular2App = require('angular-cli/lib/broccoli/angular2-app');
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
...
'angular2-devise-token-auth/**/*.+(js|js.map)',
]
});
};
System.js
Open /src/system-config.ts
. Modify the file like below:
/** Map relative paths to URLs. */
const map:any = {
'angular2-devise-token-auth': 'vendor/angular2-devise-token-auth/dist'
};
/** User packages configuration. */
const packages: any = {
'angular2-devise-token-auth': {
main: 'angular2-devise-token-auth.js'
}
};
Bootstrap:
The AuthService need to know where the auth
endpoint is. So you need to pass it as an argument.
So open /src/main.ts
, inject the Auth providers, and specify your default endpoint:
import {AUTH_PROVIDERS, authService} from 'angular2-devise-token-auth';
class App {
constructor() {}
}
bootstrap(App, [
AUTH_PROVIDERS,
authService('http://url-to-auth-endpoint')
])
Use AuthService
to register and/or sign in your users. Doing so will automatically store your signed-in user in authHeaders
that will be passed to the server with each request.
import {AuthService} from 'angular2-devise-token-auth';
@Component({ ... })
export class SomeComponent {
constructor(private authService: AuthService) {
}
register() {
this.authService.signUp({
email: 'foo@bar.com',
password: '123456',
password_confirmation: '123456',
}).subscribe(res => console.log('Successful Registration: ', res));
}
signIn() {
this.authService.signIn({
email: 'foo@bar.com',
password: '123456'
}).subscribe(res => console.log('Signed In successfully: ', res));
}
}
Use AuthHttp
instead of Http
in your services to automatically include devise authorization headers in each request.
import {AuthHttp} from 'angular2-devise-token-auth';
@Injectable()
export class SomeService {
thing: string;
constructor(private authHttp: AuthHttp) {}
getThing() {
return this.authHttp.get('http://example.com/api/thing');
}
}
npm test
Follow the GitHub Flow
Pull Requests always will be welcome :metal: