how to integrate regular username/password login with 3rd party social login for a Spring Boot + Angular single page web app? - angularjs

I have a Angular + Spring boot single page web app. The server also acts as an Auth Server which issues tokens for the angular app to use to make Restful API calls.
My old login flow uses a grant_type=password POST call to the /oauth/token endpoint to get a Bearer token. And all further API calls on behalf of the user will include the Bearer token as the "Authorization" http header.
Now I need to integrate social login (facebook, twitter, etc.), which means I don't have username/password to generate tokens so I'm not sure how to make it work.
I have been using the following two tutorials as my template:
Spring Security and Angular JS
Spring Boot and OAuth
In the first tutorial's oauth-vanilla example, the username passwork login flow brings up the authorization page. But I'd like to have the traditional username/password form login experience (log user in directly instead of showing the Authorization page).
In the second tutorial, after facebook login, I'd like to use the facebook id to look up my internal user database and create a new user if not exist and logs him in as the user. And use the internal db user's identity and authorities to authorize future API calls to my API server.
I have a stripped down sample at at
https://github.com/dingquan/spring-angular-oauth
I can make POST calls to /oauth/token endpoint and use the returned token to make further api calls to my protected /api/blogs endpoint. But I haven't figure out how to make the following things work:
Username/password login that will create a session cookie so I don't need to send the Authorization bearer token for future API calls to the resource endpoint
After facebook login (the facebook login link is under the username/password login form), calls to my endpoint still fails with 401 error (I have a "test" button that makes a get call to /api/blogs, you can click on it to see the behavior). So what am I missing to make the API call succeed?
=== UPDATE ===
Just to clarify. Here are the goals I'm trying to achieve:
multiple ways of authentication (traditional username/password, third party oauth login such as facebook, possibly cellphone number + SMS code in the future)
we do need our own user model backed by DB to store other user attributes, pure social login is not enough
social login needs to be implicit. Meaning user should not be required to create a user account in our system manually once they login through a 3rd party (facebook, etc.). We're not just grabbing users' social profile data to pre-populate the registration form. We want to create new DB users automatically behind the scene if no existing db user is associated with the given external social account. i.e. if user is logged in through facebook, they don't need to enter username/password. Authentication through facebook will automatically log the user into our system as well and user should be able to access restricted resources after facebook login.
There's some confusion that I might be asking people to put their facebook username/password in a login form hosted by my app and I'll login facebook on behalf of the user. That's not what I was asking for.

You don't need such a complicated configuration. Add #EnableOAuth2Sso to your MainConfiguration and set appropriate application properties.
Here is what I have done in order to use Facebook as a authorization server.
a) Remove clientId and authServer from UserServiceImpl. Otherwise you'll be forced to configure an authorization server that is not needed.
b) Remove AuthorizationServerConfiguration completely.
c) Add #EnableWebSecurity and #EnableOAuth2Sso to your MainConfiguration.
d) Change MainConfiguration::configure to
http
.logout().logoutSuccessUrl("/").permitAll().and()
.authorizeRequests().antMatchers("/", "/login", "/home.html").permitAll()
.anyRequest().authenticated()
.and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
e) Delete everything else except nested class AuthenticationSecurity from MainConfiguration.
f) Change ResourceServerConfiguration::configure(HttpSecurity) to
http.antMatcher("/api/**").authorizeRequests().anyRequest().authenticated();
f) Remove attribute tokenStore and method ResourceServerConfiguration::configure(ResourceServerSecurityConfigurer) from ResourceServerConfiguration.
g) Remove configuration block security and facebook from application.yml. Instead add this
security:
oauth2:
client:
client-id: <CLIENT_ID>
token-name: oauth_token
authentication-scheme: query
client-authentication-scheme: form
access-token-uri: https://graph.facebook.com/oauth/access_token
user-authorization-uri: https://www.facebook.com/dialog/oauth
resource:
user-info-uri: https://graph.facebook.com/me
client-id: <CLIENT_ID>
client-secret: <CLIENT_SECRET>
token-type: code
h) In index.html change login to login.
i) Replace the content of hello.js with this one.
But I'd like to have the traditional username/password form login experience (log user in directly instead of showing the Authorization page).
I would never use a site that requires my credentials without redirecting me to the origin! I don't know you and you are under suspicion being a phishing site.
You should really reconsider your decision.
Btw, I created a pull request with these changes.

Related

IdentityServer4: How to set a role for Google user?

I have 3 applications:
An IdentityServer4 API which provides Google authentication and also provides an access token to authorize the resource API.
A simple Resource API which provides some data from DB.
A simple Client in React which have 4 buttons:
Login, for Google auth
Logout
Get data - a simple request with the access token to the Resource API and gets the data from Db
Get user data - returns user profile and token (for debug purpose)
I didn't put any sample code because my problem is not code related, it's knowledge that I'm missing and I ask for guidance.
The workflow is working just fine: the user press the Login button, it is redirected to IdentityServer4 API for Google Auth. From there it is redirected to a Callback Page from the Client and from there to the Index page. I receive the user data and the token, I can request data from the Resource API and it's working.
My problem is: How do I give a Role to the Google Users ?
I don't have users saved in DB. I want three types of Users: SuperAdmin, Admin, Viewer and each of these roles have limited Endpoints which can access.
For limiting their access I saw that I can use Claims-based authorization or Role-based authorization.
So, my question is how ca I give a Google User who wants to login in my app, a specific Claim/Role ? What is the workflow ? I must save it first in DB ? Or there exists a service from Google where I can add an email address and select a Role for that address ?
Thank you very much !
After you get the response from Google in your callback you can handle the user and do what ever you want to do with it. Below are the some typical tasks that you can do in callback that I took from documentation page of identityserver4 link:
Handling the callback and signing in the user
On the callback page your typical tasks are:
inspect the identity returned by the external provider.
make a decision how you want to deal with that user. This might be
different based on the fact if this is a new user or a returning
user.
new users might need additional steps and UI before they are allowed
in.
probably create a new internal user account that is linked to the
external provider.
store the external claims that you want to keep.
delete the temporary cookie
sign-in the user
What I would do is creating an new internal user account that is linked to the external provider and add a role to that user.
If you don't want to save users in db, you can add an extra claim to user in callback method and use that claim in token. and i think this link will help with that.

IdenityServer4 - doesn't redirect after MFA

My Auth Server uses IdentityServer4.
Redirect configured as follows for a client
RedirectUris = new List<string>
{
"https://localhost:44342/signin-oidc"
}
this works fine for those users for whom MFA is not enabled. But when it is enabled, and kicks in, the redirect doesn't work. After successful 2nd FA, user stays back on the AuthServer page.
Any idea why?
Multifactor authentication is not implemented by Identityserver4. Identityserver4 is about how the third party application gets access to protected resources on behalf of the user.
The means of how the user gets authenticated are out of the identityserver4 scope. In other words, this is not related to identityserver4.
If you're using the identityserver4 quickstart it comes with ASPNET Identity, ASPNET Identity provides you with a local authentication system for ASPNET applications. MultiFactor Authentication is probably there.
Being said that, when you try to POST to the /authorize endpoint (note authorize not authenticate) from your client application IdentityServer tries to authorize your request and to do so it makes you authenticate first, by presenting you the Login Form.
If you look at the Address bar on this point, you'll notice there's an encoded url as returnUrl param, on the controller code you'll see a check that if that param is present, redirect to that url after successful login.
So, check the flow on your application and see where does that parameter get lost on the redirect hell, at some point you're not passing the returnUrl.

What is the right way to start Authorization Code Flow from identity server login page?

I'm trying to implement Authorization Code Flow for SPA React client with ASP.NET Core and IdentityServer4.
There are two scenarios:
1) User open SPA app, we check if he has an access token and if he hasn't we generate url like
/connect/authorize?
client_id=*client_id*&
redirect_uri=*redirect_uri*&
response_type=code&
response_mode=fragment&
state=*some_state*&
nonce=*some_nonce*&
code_challenge=*code_challenge*&
code_challenge_method=S256&
scope=openid profile email
And so Authorization Code Flow starts. This works pretty clear and after all round trips user comes back to SPA app with code then send request for token (include code and code_verifier) then receive it and with happiness in soul continue using our great application.
2) User opens login page directly and here is where I'm stuck. IdentityServer context knows nothing about this user, code challenges etc. because we didn't make request to /connect/authorize before going to this page as in normal flow. What's next?
I can generate /connect/authorize link directly in login page and do ugly redirect to it and then back to login page (what I don't want to do honestly), but how my SPA app will know what code_verifier I generate here? Of course I can store it in some shared cross-domain cookie, but here should be something better approach I believe.
Another solution I can redirect user from login page to my app, it recognizes that user not authorized and we start scenario #1. Also not my go to approach I think.
What should I do in case user opens my identity server page directly?
Is this possible using Authorization Code Flow or should I consider combine some other flows with this one?
I don't want to use Implicit Flow due to new recommendation from OAuth 2.0 specification.
Quite a simple answer to this - in your second scenario - if your user opens IDP login page directly, they didn't want to go to your app. It's the same if you were using Google or Facebook or one of the other known IDP's for your SPA and as a user I just went to their login page instead. They couldn't possibly know if my intention was to ever come to login so that I am later redirected to your SPA.
Now having said all that - what you could do to make this work somewhat seamless - is to redirect to your SPA's protected page after the user logs in through Identity Server 4 (that's simple because you own the login pages and there is no OAuth involved here). Your SPA would then be triggered to initiate the OAuth2 flow and would redirect back to Identity Server 4. The user has already logged in just seconds ago here though, so the login procedure would be skipped and user would either be presented with consent page or if your client is configured to skip consent page - user would be redirected back to your SPA with the usual tokens and such.
So to break it down into the flow:
User Accesses IDS4 Login Page -> User Enters Credentials -> IDS4
Authenticates User and Redirects to your SPA protected page -> Your
SPA initiates OAuth2 flow and redirects back to IDS4 -> IDS4 displays
consent page -> IDS4 issues auth code back to your SPA.
There is ofcourse extra step here that your SPA will exchange auth code for access token, but I omitted it for clarity purpose as it's not relevant to the question.

Google OAuth2 flow and id_token refresh

I am having troubles in implementing OAuth in the right way.
I use a client/API architecture (Angular for front and Node.js for back) and I would like user to sign in using Google OAuth authentication only.
Here is what I think is the right way for the moment (tell me if I misunderstood something) :
Angular open a Google popup asking user's consent.
Once the user agree, Google Authorization server sends back to angular a verification code.
This verification code is forwarded to an API endpoint.
Then, the API asks Google Authorization server to exchange this code for an access_token, an id_token and a refresh_token.
Google sends those 3 tokens.
The API uses access_token to retrieve user from Google API
The API persists the user
Here is the little dillema, in my opinion, the access_token and refresh_token should be stored into the database and the id_token should be sent back to Angular client.
This way, it would allow the API to ask for resource in Google API and if the token expires it can still ask for a new token thanks to the refresh_token.
Client-side, the id_token is embedded in all requests thus allowing the API to identify the client and verify his authentication with Google certs from https://www.googleapis.com/oauth2/v3/certs.
Supposing this is right way to use tokens, how could I deal with id_token expiration since client does not have any refresh token ?
Thanks !
I do it slightly different (I have the same basic architecture though).
Angular decides the user needs to log in and displays a login popup.
The url in the login popup is not serviced by angular, but is instead directly run off of the backend server: /auth/google . (I use hapijs and bell, personally).
/auth/google is serviced by a bell plugin and initiates the OAUTH dance.
the end of the OAUTH dance results in my node server generating a local token (I just generate random bytes and store them in redis mapped to user ids)
because the initial login popup was created by window.open, the success page (generated on the api side rather than in angular) can use window.opener.postMessage to communicate the token back to the angular runtime.
This way, all my sensitive google credentials (the user's oauth token, refresh token if needed, and my application's api ID and secret) are only on the server, except for during the OAUTH dance relay when they're in a URL string during the client redirects. This is reasonably secure.
Then for all the actual user interactions with the api, I use the token I generated in step four to authenticate. This could be a JWT if you wanted, but I don't do it that way; I just use redis to map from 'longrandostring' -> userId. That lets me (for example) force everyone to re-login if I wipe the redis database that has all the tokens stored, or I can write a lua script to delete all the entries that map to a certain userid.
If you need a refresh token, you can set access_type=offline in the initial request to oauth2/auth, and you'll get a refresh token as part of the response, unless you've previously gotten a refresh token. You can then persist it on the server side and get new access tokens as needed. If you set approval_prompt=force as well, you'll force a new consent screen and be guaranteed a refresh token (but after some small number of refresh tokens granted to a user, older ones expire on the same application so it's best to only request them if really needed).

Siteminder SSO + Spring Security + Angular JS

I have seen lot of examples where, there is a custom Login page with Angular JS, and then we make a rest POST call with the username/pwd, and then Spring authenticates based on whatever Auth Service we provide. Then we receive a success, grab the user object from Spring Security and then create a Session cookie in Angular.
https://github.com/witoldsz/angular-http-auth/blob/master/src/http-auth-interceptor.js
I also have seen, integrating Siteminder with Spring Security where we install a policy agent on the web server, and then grab request headers with Spring Security, and then pull the roles and build a user profile object.
I'm looking for a solution where I can combine both the above. This is the scenario :
When the user requests for index.html (Angular), the policy agent on the web server intercepts, authenticates with a Siteminder login page and then passes the headers to the app server. The Spring Security on app server will read the headers and pull the roles from our app database and then build a userprofile object. Now here, I want to continue the flow and display angular page, but Im trying to figure out, how do I send the user profile object to angular, because angular is not making a POST call at this point. Also, how do I get the http-auth-interceptor in play, because I need to keep checking if the user is still authenticated on the change of every view/state in Angular.
Help appreciated ! Thanks !
You may implement a tiny JSON REST service "/your-app/profile" which is protected by SiteMinder, reads and evaluates the headers and returns the result as a JSON object.
Your Angular App (e.g. /your-app/index.html) should better also be protected by SiteMinder so you receive an immediate redirect to the SSO Login when accessing it without session. In addition, it must read the JSON REST resource "/your-app/profile" when loaded. It must also expect that SMSESSION is missing when reading "/your-app/profile" and react accordingly - perform a reload of the protected index.html page to trigger a SM SSO re-login (if "/your-app/index.html" is protected, otherwise you must trigger login by a redirect to some protected resource).
If you want to constantly check to see if SiteMinder session is still present, you may either access the "/your-app/profile" or check for the presence of the SMSESSION cookie (only in case it is not set as HTTP-only).
One SECURITY NOTE: If you rely on the seamless SSO which is provided via SMSESSION cookie, be aware of the possible CSRF (Cross-Site Request Forgery) attacks!
Apparently both roles and the username will be available in spring if the integration is done as this describes
Integrating Spring Security with SiteMinder

Resources