I'm trying to implement a simple OpenID Connect react-admin login using gitlab as OAuth2 service provider.
most of the react-admin examples about OpenID is simple username/password login. But OpenID Connect will do several redirects, and what I come with is make python/flask server redirect to http://example.com/#/login?token=<token>, and make react-admin to parsed the URL, and set token in localStorage.
basically is somethings like below:
(({ theme, location, userLogin } ) => {
let params = queryString.parse(location.search);
if (params.token) {
userLogin({token: params.token});
}
return (
<MuiThemeProvider theme={ theme }>
<Button href={ '/api/gitlab/login' }>
Login via GitLab
</Button>
</MuiThemeProvider>
);
});
Obviously, that is not good enough, I want to have some advice about how can I improve this?
I assume you followed this example https://marmelab.com/react-admin/Authentication.html, that does not cover the OAuth2 password grant.
// in src/authProvider.js
import { AUTH_LOGIN } from 'react-admin';
export default (type, params) => {
if (type === AUTH_LOGIN) {
const { username, password } = params;
const request = new Request('https://mydomain.example.com/authenticate', {
method: 'POST',
body: JSON.stringify({ username, password }),
headers: new Headers({ 'Content-Type': 'application/json' }),
})
return fetch(request)
.then(response => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
}
return response.json();
})
.then(({ token }) => {
localStorage.setItem('token', token);
});
}
return Promise.resolve();
}
The GitLab guys / girls describe what grants they provide.
https://docs.gitlab.com/ee/api/oauth2.html#resource-owner-password-credentials-flow
Here is the example how you can get an access token using curl:
echo 'grant_type=password&username=<your_username>&password=<your_password>' > auth.txt
curl --data "#auth.txt" --request POST https://gitlab.com/oauth/token
With the access token you can get some information from the user that is also described here: https://docs.gitlab.com/ee/api/oauth2.html#access-gitlab-api-with-access-token
Here is the example how you can get information from GitLab with the access token that you got from the previous call using curl:
curl --header "Authorization: Bearer OAUTH-TOKEN" https://gitlab.com/api/v4/user
With some small adjustments in the react-admin example you can use the password credentials flow.
Here you can find the example that works with GitLab:
https://gist.github.com/rilleralle/b28574ec1c4cfe10ec7b05809514344b
import { AUTH_LOGIN } from 'react-admin';
export default (type, params) => {
if (type === AUTH_LOGIN) {
const { username, password } = params;
const oAuthParams = {
grant_type: "password",
username,
password
}
const body = Object.keys(oAuthParams).map((key) => {
return encodeURIComponent(key) + '=' + encodeURIComponent(oAuthParams[key]);
}).join('&');
const request = new Request('https://gitlab.com/oauth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body
})
return fetch(request)
.then(response => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
}
return response.json();
})
.then(( {access_token} ) => {
localStorage.setItem('token', access_token);
});
}
return Promise.resolve();
}
I hope this helps you.
Cheers
Ralf
Here an good example using oauth flow in react-admin auth provider:
https://github.com/marmelab/ra-example-oauth/blob/master/app/src/authProvider.js
Related
I'm using next-auth to authenticate users in a NextJS app, when authenticated the express api sets a token cookie that I want to use later for api routes protection. Now the authentication works, but the cookie doesn't get saved in the cookie storage in the browser although it does on Postman.
here's my credentials provider code
CredentialsProvider({
async authorize(credentials) {
try {
const {data} = await axios.post(`${process.env.URL}/api/v1/auth/login`, {
email: credentials.email,
password: credentials.password,
}, {
headers: {
'Content-Type': 'application/json'
}
})
if (data) {
return {
username: data.username,
email: data.email,
}
} else {
return null
}
} catch (error) {
return null
}
}
})
I have a SPA which uses the solution provided here to authenticate with Azure AD and everything works as expected. Now I want to migrate this to use MSAL.js.
I use below for login:
import * as MSAL from 'msal'
...
const config = {
auth: {
tenantId: '<mytenant>.com',
clientId: '<myclientid>',
redirectUri: <redirecturi>,
},
cache: {
cacheLocation: 'localStorage',
}
};
const tokenRequest = {
scopes: ["User.Read"]
};
export default {
userAgentApplication: null,
/**
* #return {Promise}
*/
initialize() {
let redirectUri = config.auth.redirectUri;
// create UserAgentApplication instance
this.userAgentApplication = new MSAL.UserAgentApplication(
config.auth.clientId,
'',
() => {
// callback for login redirect
},
{
redirectUri
}
);
// return promise
return new Promise((resolve, reject) => {
if (this.userAgentApplication.isCallback(window.location.hash) || window.self !== window.top) {
// redirect to the location specified in the url params.
}
else {
// try pull the user out of local storage
let user = this.userAgentApplication.getUser();
if (user) {
resolve();
}
else {
// no user at all - go sign in.
this.signIn();
}
}
});
},
signIn() {
this.userAgentApplication.loginRedirect(tokenRequest.scopes);
},
And then I use below to get the token:
getCachedToken() {
var token = this.userAgentApplication.acquireTokenSilent(tokenRequest.scopes);
return token;
}
isAuthenticated() {
// getCachedToken will only return a valid, non-expired token.
var user = this.userAgentApplication.getUser();
if (user) {
// get token
this.getCachedToken()
.then(token => {
axios.defaults.headers.common["Authorization"] = "Bearer " + token;
// get current user email
axios
.get('<azureapi-endpoint>' + '/GetCurrentUserEmail')
.then(response => { })
.catch(err => { })
.finally(() => {
});
})
.catch(err => { })
.finally(() => { });
return true;
}
else {
return false;
}
},
}
but after login I get below error:
Access to XMLHttpRequest at 'https://login.windows.net/common/oauth2/authorize?response_type=code+id_token&redirect_uri=<encoded-stuff>' (redirected from '<my-azure-api-endpoint>') from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Also the token that I get seems to be invalid as I get 401 errors trying to call api using the token. Upon checking the token against https://jwt.io/ I get an invalid signature.
I really appreciate anyone's input as I've already spent good few days and haven't got anywhere yet.
I'm not sure if this is your issue. however, for msal.js, in the config, there is no tenantId parameter, it's supposed to be authority. Here is a sample for graph api using msal.js
https://github.com/Azure-Samples/active-directory-javascript-graphapi-v2
specifically: the config is here: https://github.com/Azure-Samples/active-directory-javascript-graphapi-v2/blob/quickstart/JavaScriptSPA/authConfig.js
as per here, https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-js-initializing-client-applications it is supposed to be hitting login.microsoftonline.com not login.windows.net
I am building a React Native app using Expo and AWS Cognito with AWS Amplify, and I am trying to enable signing in with Facebook, Google, etc. using AWS
I can create a user and sign in using Cognito APIs without any issue.
Using third-parties, though, requires using the Expo AuthSession functionality.
The functionality itself works fine, and I am able to get all the way to retrieving the proper tokens from my /oauth2/token endpoint.
However, as far as Amplify is concerned (and I am aware), the user is not signed in, so when I try to get Auth.currentAuthenticatedUser(), null is returned.
// Open URL in a browser
openURL = async (url) => {
let result = await AuthSession.startAsync({ authUrl: url })
this.getTokenbyCode(result.params.code)
};
getTokenbyCode = async (code) => {
const details = {
grant_type: 'authorization_code',
code,
client_id: '10eavoe3ufj2d70m5m3m2hl4pl',
redirect_uri: AuthSession.getRedirectUrl()
}
const formBody = Object.keys(details)
.map(
key => `${encodeURIComponent(key)}=${encodeURIComponent(details[key])}`
)
.join("&");
await fetch(
'https://presentor.auth.us-west-2.amazoncognito.com/oauth2/token',
{
method: "POST",
headers: {
'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: formBody
}
)
.then(async (res) => {
console.log('res: ', res);
let resJSON = await res.json();
let idToken = await resJSON.id_token;
let decodedToken = jwt(idToken);
let userData = {
Username : decodedToken["cognito:username"],
Pool : Auth.userPool
}
})
.catch(error => {
console.log('error: ', error);
});
}
When I decode the token, I see the payload as I expect, but if I want to, for example, utilize the APIs to refresh the token if it expires, I have to workaround manually (check for expiration and retrieve a new token if it's expired).
Am I missing something basic?
Ok, I figured it out. Not sure if this is the right path, but it's pretty clean and it works, so I'm good with it.
Create CognitoIdToken, CognitoAccessToken, and CognitoRefreshToken objects using amazon-cognito-identity-js
Create a user session from those tokens
Create a user from that user session
await fetch(
'TOKEN ENDPOINT',
{
method: "POST",
headers: {
'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: formBody
}
)
.then(async (res) => {
const IdToken = new CognitoIdToken({ IdToken: tokenRequestJson.id_token });
const AccessToken = new CognitoAccessToken({ AccessToken: tokenRequestJson.access_token });
const RefreshToken = new CognitoRefreshToken({ RefreshToken: tokenRequestJson.refresh_token })
try {
let userSession = new CognitoUserSession({ IdToken, AccessToken, RefreshToken });
console.log('userSession: ', userSession);
const userData = {
Username: userSession.idToken.payload.email,
Pool: userPool
};
console.log('userData: ', userData);
cognitoUser = new CognitoUser(userData);
cognitoUser.setSignInUserSession(userSession);
cognitoUser.getSession((err, session) => { // You must run this to verify that session (internally)
if (session.isValid()) {
console.log('session is valid');
this.setState({user: cognitoUser})
this.props.navigation.navigate('AuthLoading')
} else {
console.log('session is not valid: ', session);
}
})
}
catch (FBSignInError) {
console.log('FBSignInError: ', FBSignInError)
}
})
.catch(fetchError => console.log('fetchError: ', fetchError))
I am new to vue and stuck on this problem for quite some time. I have a login method that retrieves an API token and stores it in localStorage. The login API call is the only call that does not send Auth headers. After the Login every call should add the API token to the header.
When I login the interceptor does not set the new header. It needs a page refresh in the browser to work. Why is that, what am I doing wrong?
In my Login component I have this method:
methods: {
login() {
api.post('auth/login', {
email: this.email,
password: this.password
})
.then(response => {
store.commit('LOGIN');
localStorage.setItem('api_token', response.data.api_token);
});
this.$router.push('reservations')
}
}
Additionally I have this axios base instance and an interceptor:
export const api = axios.create({
baseURL: 'http://backend.local/api/',
// headers: {
// 'Authorization': 'Bearer ' + localStorage.getItem('api_token')
// },
validateStatus: function (status) {
if (status == 401) {
router.push('/login');
} else {
return status;
}
}
});
api.interceptors.request.use((config) => {
config.headers.Authorization = 'Bearer ' + localStorage.getItem('api_token');
return config;
}, (error) => {
return Promise.reject(error);
});
For my react-native app I need to make sure that before every fetch request to server the use-case below should be executed
-> check the expire date of token that is saved to redux.
--> If token is not expired, app keeps going on with requested fetch to server
--> If token expired, app immediately makes new request to refresh token without making user knows it. After successfully refreshing token, app keeps going on with requested fetch to server
I tried to implement middleware with redux-thunk, but I do not know whether it's good design or not. I just need someone experienced with redux and react to give me feedback over my middleware code.
This is how I make requests to server oveer my app's component through dispatching the checkTokenAndFetch - action creater.
url = "https://———————";
requestOptions = {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + this.props.token
}
};
dispatch(authActions.checkTokenAndFetch(url, requestOptions))
.then((data) => {
})
here is action creator - checkTokenAndFetch located in authActions.js
file where my actions located
function checkTokenAndFetch(url, requestOptions){
return dispatch => {
if(authServices.isTokenExpired()){
console.log("TOKEN EXPIRED");
authServices.refreshToken()
.then(
refreshToken => {
var arr = refreshToken.split('.');
decodedToken = base64.decode(arr[1]);
newTokenExpDate = JSON.parse(decodedToken).exp;
dispatch(writeTokenToRedux(refreshToken,newTokenExpDate));
},
error => {
Alert.alert("TOKEN refresh failed","Login Again");
Actions.login();
}
);
}
else{
console.log("TOKEN IS FRESH");
}
return authServices.fetchForUFS(url, requestOptions)
.then(
response => {
return response;
},
error => {
}
)
;
}
}
Here is isTokenExpired and refreshToken functions that I call for case of token expire, located in another file named authServices.js.
function isTokenExpired(){
var newState = store.getState();
var milliseconds = (new Date).getTime();
var exDate = newState.tokenExpDate;
return milliseconds>exDate*1000
}
function refreshToken(){
var refreshToken = store.getState();
return fetch('https://—————————', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + refreshToken.token
}
})
.then((response) => {
return response._bodyText;
})
.catch((error) => {
return error;
})
}
and my fetchForUFS function in authServices.js to make a call to server after completeing token-check(refresh) stuff.
function fetchForUFS(url,requestOptions){
return fetch(url, requestOptions)
.then((response) => {
return response.json();
})
.then((responseData) =>{
return responseData;
})
.catch((error) => {
})
}
I've read tons of redux-thunk, redux-promise and middleware documentation and I'm yet not sure whether I am implementing middleware logic truly?