IdentityServer4: How to set a role for Google user? - identityserver4

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.

Related

How should I store OAuth with my own authentication system?

I have an existing signup/login system: a user enters an email and password. The password is hashed. I store it in a database.
When a user logs in, they entire their email and password. The password is hashed, and I look up the email in the database and check that the email matches. If it does, they are logged in.
I want to add a system to let users login with a 3rd party OAuth, such as GitHub. I have that setup, but I am unsure what data to store in my database.
I was thinking I take their GitHub email as the email and then use the access token for their GitHub as the password (so I would hash it and store it.)
I think this would work, but I am worried that the access tokens could change meaning they would be locked out of their account.
If I shouldn't be using the access token as a password, what should I be using? I need to store the user's email on my database but that requires a password currently, which I can't get if they use GitHub login.
(Note that when the user logs in, I call my backend to generate an access token (JWT) which I can use to require their user details and then store it in local storage. I'd like to then be able to do the same thing with with GitHub or whatever.)
oAuth is usually for authorization. Meaning, you get an access token from the authorization server, the resource server validates it and let the user access to the data.
In your case, you "do not really need" the access token - you want to use oAuth just for the authentication. Web-applications (like StackOverflow) do this to "save the trouble" of handling the authentication flows. Meaning, if I write a secured application, I need to implement somehow the create account flow, login flow, forgot password, etc. When you use a 3rd-party authentication, you save this trouble.
However, your application does need some user-id to perform actions; so you must create a user-id in you app when a user appears for the first time. Since then, you do not need to worry about password-expiry, forgotten-password and even not for the login. When the user logs-in, you get the access token and all you need to do is to get yours app' user-id from it.
Thus, I do not see a reason why you need to store a 'password', or the access token.
Hope that makes sense.
What you are looking for is actually OpenID Connect - it's an authentication framework built on top of OAuth, which lets you log in users using external Identity Providers, like Github.
When a user logs in using GitHub then you will receive an id_token in a form of a signed JWT. You can easily verify the authenticity of the JWT - so you can easily make sure that the id token really comes from Github and presents real data. Usually one of the information in the id token will be the user's email. You can use that to look up the user in your database. You don't need any password in this case.
So, you will have two ways of finding a user in your DB - either through comparing the email and password, or by looking up the user's email from a validated id token from Github.

Firebase Auth, after logging a user from react client, how do I verify user is legitimate within my other api?

I'm trying to use Firebase authentication to sign up and login users for my react website, but after that, how do I ensure that actions made from my nodejs api (for instance creating/modifying articles) are from that logged-in user. Here's a situation:
User logs in on my website, the firebase.auth().signInWithEmailAndPassword() method is called directly by the client within react (I can't use that method on my api since it asks for the raw password and I don't want to be sending that across the web, though I could save a salt on my db and hash the password, etc. but the reason I'm using firebase auth is to avoid having to be hashing passwords and maintaining salts on my db)
User is confirmed logged in
User starts to create an article
They submit the created article, react verifies they are logged in with firebase.auth().onAuthStateChanged()
Article data is sent to my api, for instance POST somehost.com/myapi/article/create/ with the article data in the body
My api receives the request and saves the article to my database
The problem I see here is that I don't see a way to send credentials to somehost.com/myapi/article/create/ in order to verify the user before entering the article into my db, since all signup/login is done within react and firebase's auth functions don't return anything I can send to my api to verify, so essentially anyone can call that endpoint and flood my database with junk.
I would like to be able to login the user within react, but then verify the user is legit within my api for all calls the user makes to it before it sends anything to the db. How can I do this?
If your Firebase client app communicates with a custom backend server, you might need to identify the currently signed-in user on that server. To do so securely, after a successful sign-in, send the user's ID token to your server using HTTPS. Then, on the server, verify the integrity and authenticity of the ID token and retrieve the uid from it. You can use the uid transmitted in this way to securely identify the currently signed-in user on your server.
See https://firebase.google.com/docs/auth/admin/verify-id-tokens

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

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.

Secure REST Unauthenticated Account Creation

I'm designing a REST API and I've hit somewhat of an odd point. 99% of this API will be secured, but there are a few functions that need to be publicly accessible. These pertain to account creation, and initial password setting. Once they have credentials, they can access the rest of the API.
The endpoint that allows a user to create a new account via a signup form is unauthenticated. Securing this endpoint isn't really possible because I'm using AngularJS on top of nodejs, and dog-fooding my API via AJAX calls. This means I can't hide credentials anywhere to access the AccountCreation endpoint. Currently, I have the webform make an AJAX call to another endpoint and create a token that says to form is valid. Upon submission that token is validated, then removed from the database. However, this token endpoint is obviously visible in code, so not much security there. Email verification is used to 'activate' the account, then the user is given a one-time link to set their initial password, which also resides on an unauthenticated endpoint(but requires the token sent in the email).
I guess my worry is someone spamming the 'CreateAccount' endpoint, and making a bunch of accounts. In reality I guess they could simply do this via the webform as well. Is this a valid security concern? How do most places handle unauthenticated account creation webforms?
Edit: the final application will be run over https

Salesforce: impersonation using the API

I'm a Salesforce system administrator and I would like to use the Web Services API on behalf of (ie: impersonate) a Salesforce user that is part of my company.
More precisely, I'm looking for a feature similar to what Google Docs already provides: https://developers.google.com/google-apps/documents-list/#using_google_apps_administrative_access_to_impersonate_other_domain_users
Can this be done ?
Thanks !
The only way to do this is to authenticate with the API using the other user's credentials. This is a security feature that cannot be avoided.
This is should be possible if you have login access for that user and a tool to inspect a browser cookies.
When you're logged in as the test user open a cookie browser and grab the value in the "sid" cookie. This is a session id for that user and can be set in the headers of an api request instead of doing a login call.
I've haven't tried this. It's possible that this session id may only be valid for the browser and not the API. In that case you should probably just create a test user with the same profile and your email. If all else fails just ask the user to temporarily change their password and share it with you.

Resources