Showing posts with label oauth. Show all posts
Showing posts with label oauth. Show all posts

Wednesday, August 29, 2018

implement Auth0 into chrome extension with one time use tokens

Leave a Comment

Im making a chrome extension where I want to create a security method for my chrome extension to stop it from getting shared without me in the process

I have an idea to generate a token somewhere (usually some backend, maybe server of the website that gets user registrations/payments my website which I am building with worpress), send token via email, get email+token in extension, make request to webserver to verify that they're valid. This seems like a typical auth flow except the password is now the token, which is generated instead of set by the user. In other news, I have more ideas (Extension-side prng with shared seed, can check to see if token is within X generations for eg.)

I want to be able to sell tokens on my website which only allow one use to prevent the token from being shared.

I tried to setup the Auth0 for the chrome extension but I keep getting errors and the process doesnt lead to how I would want done.

youtu.be/D0M1wid1L3Q?t=353

youtu.be/D0M1wid1L3Q?t=418

is a great example of what I want to be able to do. Can anyone help me doing this? I am building my website in wordpress not hard coding it so Im not sure on How to do this exacly

If anyone can point me in a direction of what I am supposed to do or maybe provide some code that could help me?

I tried to npm innstall auth and put that in my manifest.json bit it doesnt work and it seems as if it doesnt do what I want.

I have found this url which might get me heading in the right direction:

https://auth0.com/docs/api-auth/tutorials/authorization-code-grant

I really appreciate the help Thank you <3

0 Answers

Read More

Sunday, August 12, 2018

Spring Boot 2 upgrade. permit All works with .anonymous().and() .. but why?

Leave a Comment

I had migrated Oauth2 code from Spring Boot 1.3.2 T Spring Boot 2.0.2.

The below code to permit "/auth" endpoint is not working in springBoot 2

public void configure(HttpSecurity httpSecurity) throws Exception {         httpSecurity                                 .exceptionHandling()                 .authenticationEntryPoint(customAuthenticationEntryPoint)                 .and()                 .antMatchers("/auth/**").permitAll()                 .anyRequest()                 .authenticated();      } 

/auth endpoint return 401 response.

After research I hadd added

.anonymous().and()

and it working as expected now. /auth return result with out token.

I am not able to figure out the reason, what changed in spring boot 2. ?

0 Answers

Read More

Tuesday, April 24, 2018

Spring Boot Social Login and Local OAuth2-Server

Leave a Comment

I'm currently working on a Spring Boot-Application with OAuth2-Authentication. I have a local OAuth2-Server where I receive a token when posting username and password of the local database against in my case http://localhost:8080/v1/oauth/token using Spring Boot's UserDetails and UserService. Everything works fine and nice.

But now I want to enhance my program with Facebook social login and want either log in to my local OAuth2-Server or using the external Facebook-Server. I checked out the Spring Boot example https://spring.io/guides/tutorials/spring-boot-oauth2/ and adapted the idea of an SSO-Filter. Now I can login using my Facebook client and secret id, but I cannot access my restricted localhost-sites.

What I want is that the Facebook-Token "behaves" the same way as the locally generated tokens by for instance being part of my local token storage. I checked out several tutorials and other Stackoverflow questions but with no luck. Here is what I have so far with a custom Authorization-Server and I think I'm still missing something very basic to get the link between external Facebook- and internal localhost-Server:

@Configuration public class OAuth2ServerConfiguration { private static final String SERVER_RESOURCE_ID = "oauth2-server";  @Autowired private TokenStore tokenStore;  @Bean public TokenStore tokenStore() {     return new InMemoryTokenStore(); }  protected class ClientResources {     @NestedConfigurationProperty     private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails();      @NestedConfigurationProperty     private ResourceServerProperties resource = new ResourceServerProperties();      public AuthorizationCodeResourceDetails getClient() {         return client;     }      public ResourceServerProperties getResource() {         return resource;     } }  @Configuration @EnableResourceServer @EnableOAuth2Client protected class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {      @Value("${pia.requireauth}")     private boolean requireAuth;      @Override     public void configure(ResourceServerSecurityConfigurer resources) throws Exception {         resources.tokenStore(tokenStore).resourceId(SERVER_RESOURCE_ID);     }      @Autowired     OAuth2ClientContext oauth2ClientContext;      @Bean     public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {         FilterRegistrationBean registration = new FilterRegistrationBean();         registration.setFilter(filter);         registration.setOrder(-100);         return registration;     }      @Bean     @ConfigurationProperties("facebook")     public ClientResources facebook() {         return new ClientResources();     }      private Filter ssoFilter() {         CompositeFilter filter = new CompositeFilter();         List<Filter> filters = new ArrayList<>();         filters.add(ssoFilter(facebook(), "/login/facebook"));         filter.setFilters(filters);         return filter;     }      private Filter ssoFilter(ClientResources client, String path) {         OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(path);         OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);         filter.setRestTemplate(template);         UserInfoTokenServices tokenServices = new UserInfoTokenServices(client.getResource().getUserInfoUri(),                 client.getClient().getClientId());         tokenServices.setRestTemplate(template);         filter.setTokenServices(tokenServices);         return filter;     }      @Override     public void configure(HttpSecurity http) throws Exception {         if (!requireAuth) {             http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();         } else {             http.antMatcher("/**").authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN")                     .antMatchers("/", "/login**", "/webjars/**").permitAll().anyRequest().authenticated().and()                     .exceptionHandling().and().csrf()                     .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()                     .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);         }     } }  @Configuration @EnableAuthorizationServer protected class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {     @Value("${pia.oauth.tokenTimeout:3600}")     private int expiration;      @Autowired     private AuthenticationManager authenticationManager;      @Autowired     @Qualifier("userDetailsService")     private UserDetailsService userDetailsService;      // password encryptor     @Bean     public PasswordEncoder passwordEncoder() {         return new BCryptPasswordEncoder();     }      @Override     public void configure(AuthorizationServerEndpointsConfigurer configurer) throws Exception {         configurer.authenticationManager(authenticationManager).tokenStore(tokenStore).approvalStoreDisabled();         configurer.userDetailsService(userDetailsService);     }      @Override     public void configure(ClientDetailsServiceConfigurer clients) throws Exception {         clients.inMemory().withClient("pia").secret("alphaport").accessTokenValiditySeconds(expiration)                 .authorities("ROLE_USER").scopes("read", "write").authorizedGrantTypes("password", "refresh_token")                 .resourceIds(SERVER_RESOURCE_ID);     } } 

}

Any help and/or examples covering this issue greatly appreciated! :)

1 Answers

Answers 1

One possible solution is to implement the Authentication Filter and Authentication Provider.

In my case I've implemented an OAuth2 authentication and also permit the user to access some endpoints with facebook access_token

The Authentication Filter looks like this:

public class ServerAuthenticationFilter extends GenericFilterBean {      private BearerAuthenticationProvider bearerAuthenticationProvider;     private FacebookAuthenticationProvider facebookAuthenticationProvider;      public ServerAuthenticationFilter(BearerAuthenticationProvider bearerAuthenticationProvider,             FacebookAuthenticationProvider facebookAuthenticationProvider) {         this.bearerAuthenticationProvider = bearerAuthenticationProvider;         this.facebookAuthenticationProvider = facebookAuthenticationProvider;     }      @Override     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)             throws IOException, ServletException {         HttpServletRequest httpRequest = (HttpServletRequest) request;         HttpServletResponse httpResponse = (HttpServletResponse) response;         Optional<String> authorization = Optional.fromNullable(httpRequest.getHeader("Authorization"));         try {             AuthType authType = getAuthType(authorization.get());             if (authType == null) {                 SecurityContextHolder.clearContext();                 httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);             }             String strToken = authorization.get().split(" ")[1];             if (authType == AuthType.BEARER) {                 if (strToken != null) {                     Optional<String> token = Optional.of(strToken);                     logger.debug("Trying to authenticate user by Bearer method. Token: " + token.get());                     processBearerAuthentication(token);                 }             } else if (authType == AuthType.FACEBOOK) {                 if (strToken != null) {                     Optional<String> token = Optional.of(strToken);                     logger.debug("Trying to authenticate user by Facebook method. Token: " + token.get());                     processFacebookAuthentication(token);                 }             }             logger.debug(getClass().getSimpleName() + " is passing request down the filter chain.");             chain.doFilter(request, response);         } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) {             SecurityContextHolder.clearContext();             logger.error("Internal Authentication Service Exception", internalAuthenticationServiceException);             httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);         } catch (AuthenticationException authenticationException) {             SecurityContextHolder.clearContext();             httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());         } catch (Exception e) {             SecurityContextHolder.clearContext();             e.printStackTrace();             httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());         }     }      private AuthType getAuthType(String value) {         if (value == null)             return null;         String[] basicSplit = value.split(" ");         if (basicSplit.length != 2)             return null;         if (basicSplit[0].equalsIgnoreCase("bearer"))             return AuthType.BEARER;         if (basicSplit[0].equalsIgnoreCase("facebook"))             return AuthType.FACEBOOK;         return null;     }      private void processBearerAuthentication(Optional<String> token) {         Authentication resultOfAuthentication = tryToAuthenticateWithBearer(token);         SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication);     }      private void processFacebookAuthentication(Optional<String> token) {         Authentication resultOfAuthentication = tryToAuthenticateWithFacebook(token);         SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication);     }      private Authentication tryToAuthenticateWithBearer(Optional<String> token) {         PreAuthenticatedAuthenticationToken requestAuthentication = new PreAuthenticatedAuthenticationToken(token,                 null);         return tryToAuthenticateBearer(requestAuthentication);     }      private Authentication tryToAuthenticateWithFacebook(Optional<String> token) {         PreAuthenticatedAuthenticationToken requestAuthentication = new PreAuthenticatedAuthenticationToken(token,                 null);         return tryToAuthenticateFacebook(requestAuthentication);     }      private Authentication tryToAuthenticateBearer(Authentication requestAuthentication) {         Authentication responseAuthentication = bearerAuthenticationProvider.authenticate(requestAuthentication);         if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) {             throw new InternalAuthenticationServiceException(                     "Unable to Authenticate for provided credentials.");         }         logger.debug("Application successfully authenticated by bearer method.");         return responseAuthentication;     }      private Authentication tryToAuthenticateFacebook(Authentication requestAuthentication) {         Authentication responseAuthentication = facebookAuthenticationProvider.authenticate(requestAuthentication);         if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) {             throw new InternalAuthenticationServiceException(                     "Unable to Authenticate for provided credentials.");         }         logger.debug("Application successfully authenticated by facebook method.");         return responseAuthentication;     }  } 

This, filters Authorization headers, identifies whether they are facebook or bearer and then directs to specific provider.

The Facebook Provider looks like this:

public class FacebookAuthenticationProvider implements AuthenticationProvider {     @Value("${config.oauth2.facebook.resourceURL}")     private String facebookResourceURL;      private static final String PARAMETERS = "fields=name,email,gender,picture";      @Autowired     FacebookUserRepository facebookUserRepository;     @Autowired     UserRoleRepository userRoleRepository;      @SuppressWarnings({ "rawtypes", "unchecked" })     @Override     public Authentication authenticate(Authentication auth) throws AuthenticationException {         Optional<String> token = auth.getPrincipal() instanceof Optional ? (Optional) auth.getPrincipal() : null;         if (token == null || !token.isPresent() || token.get().isEmpty())             throw new BadCredentialsException("Invalid Grants");         SocialResourceUtils socialResourceUtils = new SocialResourceUtils(facebookResourceURL, PARAMETERS);         SocialUser socialUser = socialResourceUtils.getResourceByToken(token.get());         if (socialUser != null && socialUser.getId() != null) {             User user = findOriginal(socialUser.getId());             if (user == null)                 throw new BadCredentialsException("Authentication failed.");             Credentials credentials = new Credentials();             credentials.setId(user.getId());             credentials.setUsername(user.getEmail());             credentials.setName(user.getName());             credentials.setRoles(parseRoles(user.translateRoles()));             credentials.setToken(token.get());             return new UsernamePasswordAuthenticationToken(credentials, credentials.getId(),                     parseAuthorities(getUserRoles(user.getId())));         } else             throw new BadCredentialsException("Authentication failed.");      }      protected User findOriginal(String id) {         FacebookUser facebookUser = facebookUserRepository.findByFacebookId(facebookId);         return null == facebookUser ? null : userRepository.findById(facebookUser.getUserId()).get();     }      protected List<String> getUserRoles(String id) {         List<String> roles = new ArrayList<>();         userRoleRepository.findByUserId(id).forEach(applicationRole -> roles.add(applicationRole.getRole()));         return roles;     }      private List<Roles> parseRoles(List<String> strRoles) {         List<Roles> roles = new ArrayList<>();         for(String strRole : strRoles) {             roles.add(Roles.valueOf(strRole));         }         return roles;     }      private Collection<? extends GrantedAuthority> parseAuthorities(Collection<String> roles) {         if (roles == null || roles.size() == 0)             return Collections.emptyList();         return roles.stream().map(role -> (GrantedAuthority) () -> "ROLE_" + role).collect(Collectors.toList());     }      @Override     public boolean supports(Class<?> auth) {         return auth.equals(UsernamePasswordAuthenticationToken.class);     } } 

The FacebookUser only makes a reference to the Local User Id and the Facebook Id (this is the link between facebook and our application).

This SocialResourceUtils is used to get the facebook user information via facebook API (using the method getResourceByToken). The facebook resource url is setted on application.properties (config.oauth2.facebook.resourceURL). This method is basically:

    public SocialUser getResourceByToken(String token) {         RestTemplate restTemplate = new RestTemplate();         String authorization = token;         JsonNode response = null;         try {             response = restTemplate.getForObject(accessUrl + authorization, JsonNode.class);         } catch (RestClientException e) {             throw new BadCredentialsException("Authentication failed.");         }         return buildSocialUser(response);     } 

The Bearer Provider is your local Authentication, you can make your own, or use the springboot defaults, use other authentication methods, idk (I will not put my implementation here, thats by you).

And finally you need to make your Web Security Configurer:

@ConditionalOnProperty("security.basic.enabled") @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {     @Autowired     private BearerAuthenticationProvider bearerAuthenticationProvider;      @Autowired     private FacebookAuthenticationProvider facebookAuthenticationProvider;      @Override     protected void configure(HttpSecurity http) throws Exception {         http.csrf().disable();         http.addFilterBefore(new ServerAuthenticationFilter(bearerAuthenticationProvider,                 facebookAuthenticationProvider), BasicAuthenticationFilter.class);     }  } 

Notice that it has the annotation ConditionalOnProperty to enable/disable on properties security.basic.enabled. The @EnableGlobalMethodSecurity(prePostEnabled = true) enables the usage of the annotation @PreAuthorize which enables us to protect endpoints by roles for example (using @PreAuthorize("hasRole ('ADMIN')") over an endpoint, to allow acces only to admins)

This code needs many improvements, but I hope I have helped.

Read More

Wednesday, April 11, 2018

LinkedIn authentication stopped returning formatted picture

Leave a Comment

My app uses LinkedIn authentication along with a couple of other social network logins.

Even though authentication is working fine, all of a sudden LinkedIn stopped returning the formatted profile picture i.e. picture-url. I do however continue to receive the original image i.e. picture-urls -- see below: enter image description here

In my authentication request, I request r_basicprofile and r_emailaddress and according to this link, I should be receiving both the formatted and the original image. https://developer.linkedin.com/docs/fields/basic-profile

Up until 10 days ago or so, I was receiving both images. I didn't make any changes to my code but for some reason, the formatted image doesn't show up anymore. Any idea why and how to fix this?

UPDATE: All of a sudden I started getting both images again -- without making any changes to my code.

I also noticed that the image URL has now changed and I'm seeing all types of parameters in there -- such as image size, something that looks like API version type (alpha in the example below) and possibly a time stamp indicator:

https://media.licdn.com/dms/image/{image-id}/profile-displayphoto-shrink_100_100/0?e=123456789&v=alpha&t={sometypeofid} 

I don't remeber seeing any of these parameters in the image URL which is not a URL at all but what seems to be an API call that returns an image.

I don't know if LinkedIn announced such changes that I missed or just decided to make these changes without keeping developers in the loop. I hope it's not the latter and I simply missed the announcement.

0 Answers

Read More

Wednesday, March 21, 2018

Instagram OAuthException code 400, without specific reason

1 comment

Our app allows users to sign in with Instagram. Everything works well in general but one user just submitted the issue:

  • When he tries to authorize in IG from our app, he receives the following error:

{"error_type":"OAuthException", "code":400, "error_message":"There was an error with your request. Please try again."}

Trying again does not help. He still sees the issue and cannot connect his IG account.

Can anyone help at least with the direction we have to follow in our investigation?

1 Answers

Answers 1

Answer by h0mayun seems to work:

For me unchecking Disable implicit OAuth in instagram developer -> manage clients fixed the issue

Read More

Tuesday, December 12, 2017

Getting the Auth Token for the secondary Id from Google chrome extension using OAuth 2.0 & Client ID

Leave a Comment

I am fairly new to developing chrome extensions, more specifically to the user authentication part in chrome extensions. I am following User Identity example from Google Developer docs.

The example works perfectly fine. I was able to generate the client id for the chrome app, add the scope for api's in my case gmail api. And finally get the Auth Token by adding the identitypermission in manifest.json as follows

"oauth2": {     "client_id": "MY CLIENT ID",     "scopes": [       "https://www.googleapis.com/auth/gmail.readonly",       "https://www.googleapis.com/auth/gmail.modify"     ]   } 

And my app.js is a content_script which has the following code.

chrome.identity.getAuthToken({ 'interactive': true }, function(token) {     /* With which i can use xhr requests to get data from gmail api */       console.log('Access Token : '+token); }); 

Now this token that i get gives me the result for the user with which i have logged into chrome. Meaning Lets say i have a UserA with email address user_a@gmail.com and i have used this log into the chrome browser.

Question

How do I get the associated accounts or the secondary accounts. For instance lets say a User B logs into Gmail from the chrome browser. Is it possible to access the gmail api for that particular user who is currently logged in ?

I have tried a couple of things here ..

gapi.auth.authorize({             'client_id': CLIENT_ID,             'scope': SCOPES.join(' '),             'immediate': true           },            function(authResult){//do something}); 

In the above scenario, the client id and scopes are fetched from the manifest.json using chrome.runtime.getManifest();.

  • This method uses the client.js from google api's and makes use of gapi variable.
  • In this case, i get the access token for the user whom i generated the client id , not even the chrome application user.
  • Furthermore, When i open a incognito mode and access this plugin, still i get the same users access token.

Additional Note

I tried the same gapi.auth.authorize() using a Web OAuth 2 Client Id. It works perfectly fine. I mean whenever this authorize is executed it fetches the current logged in user's data or it asks for a login where the user can login and authenticate. How do i achieve the same thing in chrome extension.. Kindly let me know if i am missing something here .

1 Answers

Answers 1

As of now, this is not possible using supported APIs in Google Chrome stable (Version 63). However, in the Dev channel and most likely with a future release, the following will be possible:

chrome.identity.getAccounts(function(accounts) {     // accounts is a list of accounts.     chrome.identity.getAuthToken({ 'interactive': true, 'account': accounts[0] }, function(token) {         /* With which i can use xhr requests to get data from gmail api */           console.log('Access Token : '+token);     }); }); 

See the documentation for getAccounts().


EDIT: Something that might work in the meantime is registering for the onSigninChanged event.

Read More

Monday, December 4, 2017

Spring oauth: Why resource server is authorising instead of authorisation server

Leave a Comment

What i found while using spring oauth framework is resource server making check_token?token=T_O_K_E_N request to authorisation server, and authorisation server is just returning CheckTokenEndPoint map with authorities something like below.

{     "exp": 1511471427,     "user_name": "idvelu",     "authorities": [         "FUNCTION_GET_USERS",         "FUNCTION_AUTHORITY_1",         "FUNCTION_AUTHORITY_2",         "FUNCTION_AUTHORITY_3",         "FUNCTION_AUTHORITY_4",         "FUNCTION_AUTHORITY_5",         "FUNCTION_AUTHORITY_6",         "FUNCTION_AUTHORITY_7",     ],     "client_id": "c1",     "scope": [         "read",         "write"     ] } 

Just visualise this with oauth service and resource service is running in two different machines/jvm.

I think now resource server has to authorise the request against configured valid authorities in ResourceServerConfiguration::configure(HttpSecurity) with the authorities from the authorisation server.

@Override public void configure(HttpSecurity http) throws Exception {  http.anonymous().disable().requestMatchers().antMatchers("/**").and().authorizeRequests()          .antMatchers(HttpMethod.GET, "/myproject/users").hasAnyAuthority("FUNCTION_GET_USERS")         .antMatchers(HttpMethod.POST, "/myproject/users").hasAnyAuthority("FUNCTION_POST_NEW_USER")         .anyRequest().denyAll()         .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler()); } 

In this case authorisation server may return all the hundreds of user authorities to resource server. Instead why not authorisation server itself can take the few of the permission required for authorisation as query params
check_token?token=T_O_K_E_N&authorities=FUNCTION_GET_USERS,FUNCTION_AUTHORITY_2,..
from the resource server and validate it against the user's functions through DB?

And finally my problem is; i have different services like java, node.js, NGINX... All these have to verify its authentication and authorization against one spring Authorisation server. Because of the above stated problem all my service has to implement the authorisation (resource server) part. Means comparing all the authorities of user against the API acess authorities.
Java side this comparison is fine with spring resource server implementation. But all other non-java (resource) services needs authorisation/resourceServer implementation. Instead if my spring authorisation server accepts the authorities and validates then my problem is solved as single point of authorisation/comparison implementations. I just need to pass it as part of check_token.

How to implement this new check_token endpoint along with accepting the authorities?

1 Answers

Answers 1

The authorization server is responsible for authenticating the user/client (depending on the oauth type you use). When this is done, a token is given.

When a user/client presents themselves to the resource server, wanting to consume a service, they must provide the token. Now the resource server has a token and needs to validate that this token was generated by the authorization server. There are two options:

  1. The token itself does not contain any information. The resource server calls the authorization server and asks if the token is valid. The authorization server will respond that the token is valid and gives some additional information (user/client, roles/scopes, etc).
  2. The token does contain the necessary information (JWT tokes for example). This enables the resource server to extract the needed info without contacting the authorization server. In this case, the authorization server has signed the token and the resource server can validate the signature to be sure that it was the autorization server that has issued the token.

At the moment, you are using the first scenario. Every resource server you write, must verify tokens and extract additional info. How the verification is done depends on the authorization server.

Part2:

Your question is not clear to me. I presume you are using the OAuth2 authorization code scheme with non JWT tokens?

In that case, you have an authorization server that is only responsible for authentication, a resource server that is exposing some services and a client that consumes the resource server.

If i'm not mistaking, you have different resource servers (api's)?

You did not share your authorization server configurations, but normaly you use @EnableAuthorizationServer. This will create an endpoint /oauth/check_token. By default this endpoint is not accassible. You need to do something like this:

@Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {    oauthServer.checkTokenAccess("permitAll()"); // authenticated is better } 

You can use this endpoint to validate tokens.

All this is described in the oauth2 developer guide.

Part3:

On the authorization server, you can create an endpoint like this :

@RequestMapping("/user") public Principal user(Principal principal) {      if(principal instanceof OAuth2Authentication) {         return (OAuth2Authentication) principal;     } else {         return principal;     } } 

You can modify it to your needs.

Read More

Monday, November 27, 2017

How to convert OAuth code with an access token

Leave a Comment

Imagine you're going through a standard OAuth2 process to retrieve an access_token for some third-party API. This is the usual process.

  1. User is redirected to http://some-service.com/login
  2. User successfully logs in and is redirected to some destination http://some-destination.com. In this step, there's usually a code parameter that comes with the request. So the actual URL looks like http://some-destination.com?code=CODE123
  3. I need to use CODE123 to request an access_token that can be used to authorize my future API calls. To do this, there's an endpoint that usually looks like this (I am using Nylas as an example but should be generic enough):

enter image description here

As you can see, it requires me to POST the code from above (CODE123) along with client_id and client_secret like this: http://some-service.com/oauth/token?code=CODE123&client_secret=SECRET&client_id=ID. As a response, I get an access_token that looks like TOKEN123 and I can use this to make API calls.

QUESTION

Until step 2, everything happens in the client side. But in step 3, I need to have client_id and client_secret. I don't think it's a good idea to store these values in the client side. Does that mean I need to have a backend server that has these two values, and my backend should convert CODE123 to TOKEN123 and hand it to the client side?

1 Answers

Answers 1

As you probably know, the question describes the most common (and usually, the more secure) OAuth "Authorization Code" flow. To be clear, here's an approximation of the steps in this flow:

  1. User indicates that they wish to authorize resources for our application (for example, by clicking on a button)
  2. The application redirects the user to the third-party login page, where the user logs in and selects which resources to grant access to
  3. The third-party service redirects the user back to our application with an authorization code
  4. Our application uses this code, along with its client ID and secret to obtain an access token that enables the application to make requests on behalf of the user only for the resources that the user allowed

Until step 2, everything happens in the client side. But in step 3, I need to have client_id and client_secret. I don't think it's a good idea to store these values in the client side. Does that mean I need to have a backend server that has these two values[?]

You're correct, it's certainly not a good idea to store these values in the client-side application. These values—especially the client secret—must be placed on a server to protect the application's data. The user—and therefor, the client application—should never have access to these values.

The server uses its client ID and secret, along with the authorization code, to request an access token that it uses for API calls. The server may store the token it receives, along with an optional refresh token that it can use in the future to obtain a new access token without needing the user to explicitly authorize access again.

...and my backend should convert CODE123 to TOKEN123 and hand it to the client side?

At the very least, our server should handle the authorization flow to request an access token, and then pass only that token back to the client (over a secure connection).

However, at this point, the client-side application (and the user of that client) is responsible for the security of the access token. Depending on the security requirements of our application, we may want to add a layer to protect this access token from the client as well.

After the server-side application fetches the access token from the third-party service, if we pass the access token back to the client, malware running on the client machine, or an unauthorized person, could potentially obtain the access token from the client, which an attacker could then use to retrieve or manipulate the user's third-party resources through privileges granted to our application. For many OAuth services, an access token is not associated with a client. This means that anyone with a valid token can use the token to interact with the service, and illustrates why our application should only request the minimum scope of access needed when asking for authorization from the user.

To make API calls on behalf of a user more securely, the client-side application could send requests to our server, which, in turn, uses the access token that it obtained to interact with the third-party API. With this setup, the client does not need to know the value of the access token.

To improve performance, we likely want to cache the access token on the server for subsequent API calls for the duration of its lifetime. We may also want to encrypt the tokens if we store them in the application's database—just like we would passwords—so the tokens cannot be easily used in the event of a data breach.

Read More

Tuesday, October 17, 2017

Which OAuth flow should I use for my native app?

Leave a Comment

I'm developing an app using React Native and I couldn't find any tutorial to authenticate my users against my own service (I think this is called 1st party app). Users need to be able to authenticate with user/password and with their Facebook account as well.

I've been researching about it and find out that I should use Authorization Code Grant Flow which should work in this way:

  1. Create a log-in link with the app's client ID, redirect URL, and state parameters
  2. The user sees the authorization prompt and approves the request
  3. The user is redirected back to the app’s server with an auth code
  4. The app exchanges the auth code for an access token

As I understand all my redirect links should start with myapp://uri opening it in native browser. But I really don't need the step two, or do I? Why should I ask the user for permissions for the same service?

One more thing that I don't understand is that to exchange auth code for an access token I need to pass my Client ID and Client Secret. But I've read that I don't have to store client secrets in native apps since it can be compromised.

2 Answers

Answers 1

How have you initiated your react native app? Via create-react-native-app or Expo XDE or through the react-native init? If either of the first two options, Facebook Auth becomes pretty straight forward. Here's a link to Expo's Facebook Auth Docs. Here's a copy/paste example of what that would look like...

async function logIn() {   const { type, token } = await Expo.Facebook.logInWithReadPermissionsAsync('<APP_ID>', {       permissions: ['public_profile'],     });   if (type === 'success') {     // Get the user's name using Facebook's Graph API     const response = await fetch(       `https://graph.facebook.com/me?access_token=${token}`);     Alert.alert(       'Logged in!',       `Hi ${(await response.json()).name}!`,     );   } } 

This will (by default) attempt to authenticate via 'web', meaning it attempts to log in through a modal UIWebView pop up. There are other methods too, but they're only valid for stand alone apps (see behavior options).

I know you said you wanted to use your own service to do authentication, but I think it might be useful for you to at least go through the Auth0 React Native SDK Tutorial to get an idea how to secure client IDs and secrets as well as get an overall idea of what a good auth flow looks like. Then decide whether to rebuild everything yourself as your own service or whether to use theirs.

Answers 2

OAuth 2.0 is not an authentication protocol, it's for Authorization. That is why you are having problems with step 2. This might be interesting to read.

For your flow I think you have 2 options.

  1. Implicit flow, no client secret. (This would be my first choice)
  2. Use the Authorization Code Grant Flow and don't care about the secret. Do make sure you check on your server if the redirecturl is correct.
Read More

Wednesday, October 4, 2017

Oauth1 iOS get data from API

Leave a Comment

How to get data from API with Oauth1? I just tried like this but it did not work.

import UIKit import OAuthSwift  class TestLogin: UIViewController {  var oauthswift: OAuthSwift? final let urlString = "https://conversation.8villages.com/1.0/contents/articles"   override func viewDidLoad() {     super.viewDidLoad()      self.doOAuth() }   func doOAuth() {       let oauthswift = OAuth1Swift(         consumerKey:    "******",         consumerSecret: "******",         requestTokenUrl: "https://oauth.8villages.com/tokens/request-token",         authorizeUrl:    "https://accounts.8villages.com/oauth/request-token",         accessTokenUrl:  "https://accounts.8villages.com/oauth/access-token"     )       oauthswift.authorize(         withCallbackURL: URL(string: "https://8villages.com")!,         success: { credential, response, parameters in             print(credential.oauthToken)             print(credential.oauthTokenSecret)             print(parameters["userId"])     },         failure: { error in             print(error.localizedDescription)     }                  ) }  func getHandleURL () {     let url = NSURL(string: urlString)     URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: { (data, response, error) -> Void in          if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {              print(jsonObj!.value(forKey: "data"))          }      }).resume() }  } 

so, how must I do or I need a reference example get data from API with Oauth1? I just don't know how to start to build project with OAuth because I search in google, only tutorial OAuth for login with social media.

1 Answers

Answers 1

In order to send oAuth 1.0 request basically you need to calculate proper query string and body parameter which actually based on your server implementation.

You need to get following query param:

  • oauth_consumer_key
  • oauth_nonce
  • oauth_signature_method
  • oauth_timestamp
  • oauth_version

You can check this blog where all the params are explained in very good detail and also the signature process. Also this answer guide you how to create HMAC-SHA1 signature in iOS

In the end of this process you need to create signature based on signature method which your app and server both agreed upon.

Then a sample POST request should look like following: Which is taken from oAuth1 guide

POST /wp-json/wp/v2/posts Host: example.com Authorization: OAuth                oauth_consumer_key="key"                oauth_token="token"                oauth_signature_method="HMAC-SHA1"                oauth_timestamp="123456789",                oauth_nonce="nonce",                oauth_signature="..."  {     "title": "Hello World!" } 

Hope it helps.

Read More

Monday, October 2, 2017

Angular sending access token to Asp.net Web API not working if the email address has a '+' in it

Leave a Comment

I have security working fine in an application, except when a user tries to login with a '+' in their email.

The access token looks fine (when the email contains a + it looks like this):

Bearer 8BGpt_KkEp-_6U5tUdKqK1xLCQBaWzHcxDT9RRKkbzoF2fHCUNhRL3U-fpLdQIuSXm8RcTOH4ZY3a0UZH6-6IgXxx_ojgyL26179JovRm5xQSZD7ANxLvvdU3ubfcpzSr4tw-sza37UaJh7xDFB8eH0NA9Djt7Ik8Ebxdin7u-n76InCulRAV6xMWgXfF9bwoU8MsV3lrh_zhnxYGnx3O7QUNQ740NUJLHJYH12rBth16CA1AXSF86rA5rUB7vJ7yK09k_FJTifyuldTeFHJHsyscnEIQxGozbf3x1cmZowkiK4Q1r8W0M8uz25m8j_tuMrWawTqYJNZiTuI9afW38WWQ4BRLkQF7TwoMOgZQ-f1K_3W8Zy3x-OsKdQS4i9CapvKe1utCscZVroByvyD9SvpILGiZGTjGD_zCAm8KerMPT5GNOb07kPGV_167PHEXm0TGaJbCelb5gLgXbMXv3GxBQLnYIfPUXCBaKx4UFkY8kFMPs9MxFcGY81p67rfnjeswBZ3PW6fDFTf9U_I8g 

However, when I try to send a secure request with this access token, I get the response:

status: 401 "{"Message":"Authorization has been denied for this request."}" 

As said above, it works without any issue if I remove the plus. This seems to be a Wep API issue rather than an Angular issue.

I found that the methods encodeUrl and decodeUrl to not stop the space from being change to a plus. I have tried the following in the c# code to switch the space to a plus:

var registerEmail = model.email.Replace(' ', '+'); 

This is used in both the login and register actions.

Perhaps it is not possible to use a + in an email in OAuth in Web API 2?

1 Answers

Answers 1

It seems to be a bug in asp.net roles. I am not sure of a clear solution. However, for the time being, encoding the username as follows before storing it on register and when logging in:

public static class UsernameEncodingService {     public static string returnEncodedUsername(string email)     {         var emailAsLower = email.ToLowerInvariant();         var encodedEmail = Base64Encode(emailAsLower);         var encodedEmailWithoutEquals = encodedEmail.Replace("=", "213");         var encodedEmailWithoutPlus = encodedEmailWithoutEquals.Replace("+", "214");         return encodedEmailWithoutEquals;     }      private static string Base64Encode(string plainText)     {         var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);         return System.Convert.ToBase64String(plainTextBytes);     } } 
Read More

Friday, August 18, 2017

OAuth2::Error, invalid_request: redirect_uri does not match application configuration

Leave a Comment

I'm working on a rails app that authenticates using Bungie OAuth using this gem. My configurations in initializers/devise.rb are as follows:

config.omniauth :bungie, ENV['CLIENT_ID'], ENV['CLIENT_SECRET'], ENV['X_API_KEY'], ENV['REDIRECT_URL'] 

Bungie's developer portal requires a redirect URL with HTTPS, so I've pushed my application to Heroku and used a redirect to force authentication back to localhost for testing. Using this method, everything works fine. However, when I push the app to production, the response back to my application from Bungie fails with OAuth2::Error, invalid_request: redirect_uri does not match application configuration. The redirect_url is the exact same thing in both my application's env variables and on Bungie's development portal.

Seeing as it's in production, I'm limited to the logs that I can see. I've tried tracking the requests in the network tab of the dev tools in my browser, but everything looks as it should.

I've tried working with the developer of the bungie-oauth2 gem, but we have not been able to come to a resolution (and his prod apps work fine with it).

Is there anything that might cause the redirect_url to differ once in Heroku?

As requested, here is my route for omniauth:

devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" } 

Output from rake routes:

 users_sign_out GET      /users/sign_out(.:format)             devise/sessions#destroy           new_user_session GET      /users/sign_in(.:format)              devise/sessions#new               user_session POST     /users/sign_in(.:format)              devise/sessions#create       destroy_user_session DELETE   /users/sign_out(.:format)             devise/sessions#destroy user_bungie_omniauth_authorize GET|POST /users/auth/bungie(.:format)          users/omniauth_callbacks#passthru user_bungie_omniauth_callback GET|POST /users/auth/bungie/callback(.:format) users/omniauth_callbacks#bungie          new_user_password GET      /users/password/new(.:format)         devise/passwords#new         edit_user_password GET      /users/password/edit(.:format)        devise/passwords#edit              user_password PATCH    /users/password(.:format)             devise/passwords#update                            PUT      /users/password(.:format)             devise/passwords#update                            POST     /users/password(.:format)             devise/passwords#create   cancel_user_registration GET      /users/cancel(.:format)               devise/registrations#cancel      new_user_registration GET      /users/sign_up(.:format)              devise/registrations#new     edit_user_registration GET      /users/edit(.:format)                 devise/registrations#edit          user_registration PATCH    /users(.:format)                      devise/registrations#update                            PUT      /users(.:format)                      devise/registrations#update                            DELETE   /users(.:format)                      devise/registrations#destroy                            POST     /users(.:format)                      devise/registrations#create 

and my controller:

def bungie   @user = User.from_omniauth(request.env["omniauth.auth"])    if @user.persisted?     @user.remember_me = true     sign_in_and_redirect @user, :event => :authentication   else     session["devise.bungie_data"] = request.env["omniauth.auth"]     redirect_to root_path   end end 

Full source can be found at https://github.com/destiny-aviato/destinder.

2 Answers

Answers 1

Encoding of redirect_uri param in your auth request to bungie jumps out:

https%25253A%25252F%25252Fdestinder.herokuapp.com%25252Fusers%25252Fauth%25252Fbungie%25252Fcallback 

To read it in plain, I had to decode it thrice. Normally params are encoded just once

URI.decode(URI.decode(URI.decode("https%25253A%25252F%25252Fdestinder.herokuapp.com%25252Fusers%25252Fauth%25252Fbungie%25252Fcallback"))) 

Not sure if this is what causing the issue. Can you check how many times request_uri gets encoded when you hit it from local. If it's less than 3, then during heroku deployment your request_uri gets encoded one extra time.

To get request_uri for local, logout from bungie, click on "Sign in with bungie" on your local. The url in browser would have request_uri.

Answers 2

replace redirect url of your Heroku application in credential

Read More

Tuesday, August 1, 2017

How do I get the user's email when using Microsoft Account Authentication in an MVC project?

Leave a Comment

I have modified startup.Auth.cs so that I could add scopes. Here is what I have:

MicrosoftAccountAuthenticationOptions mo = new MicrosoftAccountAuthenticationOptions() {     ClientId = "My Client ID",     ClientSecret = "My Client Secret", }; app.UseMicrosoftAccountAuthentication(mo); 

This allows me to authenticate the user.

I have tried adding the scopes wl.signin, wl.emails and wl.contacts_emails. However, they cause the Microsoft login page to report the following error: AADSTS70011: The provided value for the input parameter 'scope' is not valid. The scope wl.signin, wl.emails, wl.contacts_emails is not valid. The scope combination of openid and email seems to work. However, the scope openid is overkill for what I am trying to do. That is, I think it is too much to ask from the user. The scope email all by it self doesn't work.

This is particularly weird because the template that Visual Studio sets up assumes that the external authentication provider will supply an email address.

How do I get only the user's email?

For context, I am using the following documents: https://developer.microsoft.com/en-us/graph/docs/concepts/permissions_reference#openid-permissions which gives the impression that I want email and profile included in the scope. However, it goes on to state that they are included by default.

I am trying to implement external Authentication in my MVC project using the document: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/microsoft-logins.

3 Answers

Answers 1

You can use the following code to get the email address of a user.

 ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1]; 

Answers 2

Try to add scopes:

MicrosoftAccountAuthenticationOptions mo = new MicrosoftAccountAuthenticationOptions() {     ClientId = "My Client ID",     ClientSecret = "My Client Secret", }; mo.Scope.Add("openid"); mo.Scope.Add("email"); app.UseMicrosoftAccountAuthentication(mo); 

Answers 3

Looks like you have to use OpenID to get the email. However, If you have Microsoft.IdentityModel.Tokens v5.x you can't use OpenID. It only works with Microsoft.IdentityModel.Tokens v4.x. Made the mistake of loading the lates version.

Read More

Thursday, July 27, 2017

LinkedIn API OAuth refresh token

Leave a Comment

I am using LinkedIn API to pull updates from there and display on the website. While using OAuth, I am storing the token in a file and then pull it from there again to prevent the login popup. However, I am not clear once my token expires how will it get refreshed. Following is how I am reading the token from the file -

        $config = json_decode(file_get_contents(".service.dat"));         if( isset($config->key) && isset($config->secret) ) {             $this->access_token = new OAuthConsumer($config->key, $config->secret);         }  

For authentication I have following to get request token -

function getRequestToken() {     $consumer = $this->consumer;     $request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $this->request_token_path);     $request->set_parameter("oauth_callback", $this->oauth_callback);     $request->sign_request($this->signature_method, $consumer, NULL);     $headers = Array();     $url = $request->to_url();     $response = $this->httpRequest($url, $headers, "GET");     parse_str($response, $response_params);     $this->request_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1); } 

After generating token, I am generting authorize url:

function generateAuthorizeUrl() {     $consumer = $this->consumer;     $request_token = $this->request_token;     return $this->authorize_path . "?oauth_token=" . $request_token->key; } 

LinkedIn documentation states following about refresh token:

Refreshing an access token is very simple and can happen without an authorization dialog appearing for the user. In other words, it's a seamless process that doesn't affect your application's user experience. Simply have your application go through the authorization flow in order to fetch a new access token with an additional 60 day life span.

I am not clear what that means. If I have to redo all the way from obtaining request token again then wouldn't that require me to make http request again and having to popup the login screen? How do I avoid it? Will appreciate suggestion.

Thanks.

1 Answers

Answers 1

Found out. Authorization URL:

https://www.linkedin.com/oauth/v2/authorization

followed by the access token url:

https://www.linkedin.com/oauth/v2/accessToken

was all that I really had to do (passing with the right parameters).

Read More

Saturday, July 15, 2017

Spring Security OAuth - Provider Manager is Not Configured for Null Resource

Leave a Comment

Am trying to use Spring Secruity's OAuth API to obtain an access token from an externally published API.

This curl command works (and its contents are all that I need to obtain an access token):

curl -X POST \ https://api.app.com/v1/oauth/token \   -H 'content-type: application/x-www-form-urlencoded' \   -d'grant_type=client_credentials&client_id=bcfrtew123&client_secret=Y67493012' 

Am able to obtain an access token from the external service after running this curl command.

When using Spring Security OAuth API:

<dependency>    <groupId>org.springframework.security.oauth</groupId>      <artifactId>spring-security-oauth2</artifactId>      <version>2.1.1.RELEASE</version> </dependency> 

Setup my SpringMVC Controller's method like this:

@RequestMapping(value = "/getAccessToken", method = RequestMethod.POST, consumes="application/x-www-form-urlencoded") public OAuth2AccessToken getAccessToken(@RequestParam(value="client_id", required=true) String clientId, @RequestParam(value="client_secret", required=true) String clientSecret) throws Exception {     String tokenUri = "https://api.app.com/v1/oauth/token";      ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();      resourceDetails.setAccessTokenUri(tokenUri);     resourceDetails.setClientId(clientId);     resourceDetails.setClientSecret(clientSecret);     resourceDetails.setGrantType("client_credentials");     resourceDetails.setScope(Arrays.asList("read", "write"));      DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();      oauth2RestTemplate = new OAuth2RestTemplate(resourceDetails, clientContext);      OAuth2AccessToken token = oauth2RestTemplate.getAccessToken();     return token; } 

When I invoke the getAccessToken call from my local tomcat instance:

access_denied  error_description=Unable to obtain a new access token for resource 'null'.  The provider manager is not configured to support it. 

Question(s):

  1. What am I missing here? Is there some annotation required for this? Is there a property that is not set or is needed?

(Please notice that the content-type needs to be "application/x-www-form-urlencoded"...)

  1. How can I mimic the working curl command using Spring Security OAuth API?

  2. Could it be the default values that I have set in the RequestParameters?

  3. If successful, how can I set it up so that access token is always preloaded before any request made?

2 Answers

Answers 1

This could be oocured beacuse server doest not recognize the content type you posting to that specific url. In your CURL request try include the 'content-type: application/x-www-form-urlencoded' for custom conrtroller using http headers. Http headers

Also you have not set username and password for resourceDetails. resourceDetails.setUserName("user"); resourceDetails.setUserName("password");

if those does not work try to extract the request that Encoded with application/x-www-form-urlencoded and pass it as a string via RestTemplate and you can get the token.

Let me know any if you need additional support.

Try the code below that is giving token as and string response.

enter image description here

Answers 2

This is what i use:

@Bean public RestTemplate oAuthRestTemplate() {     ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();     resourceDetails.setId("1");     resourceDetails.setClientId(oAuth2ClientId);     resourceDetails.setClientSecret(oAuth2ClientSecret);     resourceDetails.setAccessTokenUri(accessTokenUri);      OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails, oauth2ClientContext);      return restTemplate; } 

The correct headers will be set bij the framework, but the username/password will be base64 encodes as Authorization header (basic authentication). This is the OAuth2 spec for a client_credentials grant.

Check if the api supports the spec:

curl -X POST \ 'https://api.app.com/v1/oauth/token' \ -i -u 'client:secret' \ -H 'Content-Type: application/x-www-form-urlencoded' \ -d 'grant_type=client_credentials' 

If you need to send the username & password as data instead of authorisation header, you can add resourceDetails.setAuthenticationScheme(AuthenticationScheme.form); this should set de username & password as data

Read More

Monday, May 22, 2017

UIWebView load fails with custom URL scheme

Leave a Comment

I have a UIWebView that is handling an OAuth authentication flow in my app. The callback URL that the OAuth service uses points to a custom URL scheme I've set up in my app, let's call it mycustomurlscheme.

So once the user authenticates successfully, the OAuth service redirects them to the URL mycustomurlscheme://oauth/success?oauth_token=xxxxxxxxxxxxxxxxxxxx&oauth_verifier=xxxxxxxxxxxxxxxxxxxx. When the UIWebView requests this URL, the app behaves correctly; namely, the application:openURL:sourceApplication:annotation: method in my app delegate gets called, and I dismiss the UIWebView and continue on with the app.

However, I am logging load failures in the UIWebView (using webView:didFailLoadWithError:), and when the above process happens, I see the following in the console:

Error Domain=WebKitErrorDomain Code=102 "Frame load interrupted" UserInfo=0xa1a4810 {NSErrorFailingURLKey=mycustomurlscheme://oauth/success?oauth_token= xxxxxxxxxxxxxxxxxxxx&oauth_verifier=xxxxxxxxxxxxxxxxxxxx, NSErrorFailingURLStringKey=mycustomurlscheme://oauth/success?oauth_token= xxxxxxxxxxxxxxxxxxxx&oauth_verifier=xxxxxxxxxxxxxxxxxxxx, NSLocalizedDescription=Frame load interrupted} 

I tried implementing the following UIWebViewDelegate method, thinking that intercepting the request would avoid the error, but the error still happens:

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request  navigationType:(UIWebViewNavigationType)navigationType {     if ([request.URL.scheme isEqualToString:@"mycustomurlscheme"]) {         [[UIApplication sharedApplication] openURL:request.URL];         return NO;     } else {         return YES;     } } 

This code then causes the following code in my app delegate to run:

- (BOOL)application:(UIApplication *)application             openURL:(NSURL *)url   sourceApplication:(NSString *)sourceApplication          annotation:(id)annotation {     NSNotification *notification = [NSNotification notificationWithName:kDSApplicationLaunchedWithURLNotification object:nil userInfo:@{kApplicationLaunchOptionsURLKey: url}];     [[NSNotificationCenter defaultCenter] postNotification:notification];      return YES; }  

This notification is picked up by the following block that continues the loading & launching of the app, post-authorization:

self.applicationLaunchNotificationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:kDSApplicationLaunchedWithURLNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) {                     NSURL *url = [notification.userInfo valueForKey:kApplicationLaunchOptionsURLKey];                     currentRequestToken.verifier = [DSAPIParametersFromQueryString([url query]) valueForKey:@"oauth_verifier"];                      [[DSAPIManager sharedManager] acquireAccessTokenWithRequestToken:currentRequestToken success:^(DSAPIOAuth1Token * accessToken) {                         [self finishLogin];                     } failure:^(NSError *error) {                         [self removeAsObserver];                         [self showAlert:NSLocalizedString(@"Could not authorize the app. Please try again later.", nil)];                     }];                 }]; 

The finishLogin and removeAsObserver methods look like this:

- (void)finishLogin {     [self removeAsObserver];     [self.navigationController dismissViewControllerAnimated:YES completion:^{         [self performSegueWithIdentifier:@"PostLoginSegue" sender:self];     }]; }  - (void)removeAsObserver {     if (self.applicationLaunchNotificationObserver) {         [[NSNotificationCenter defaultCenter] removeObserver:self.applicationLaunchNotificationObserver];         self.applicationLaunchNotificationObserver = nil;     } } 

Is it safe to ignore this error message? Anyone know why it's happening? My hunch is that the UIWebView thinks the URL has an invalid scheme, but the phone knows it's ok. If that's the case is there any way to tell the UIWebView (or the WebKit engine) that this scheme is valid?

2 Answers

Answers 1

The error here is actually the Frame load interrupted nothing to do with the url scheme. Using custom url scheme is perfectly possible and doesn't create any errors. I have them in many of my apps and have never had a problem with them.

I believe your issue is because of the [webView stoploading]; technically it will stop loading when you return NO so the [webView stopLoading]; is just causing an interruption in the process. Remove this line and let it continue to return NO and see what happens I am 99.9% sure this is the reason.

So your code would look like

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {     if ([request.URL.scheme isEqualToString:@"mycustomurlscheme"]) {         // Dismiss the view controller, continue loading the app, etc.         return NO;     }       return YES; // No need for the else statement if this is the only thing to happen if it fails the if statement. } 

UPDATE

Based don comments removing [webView stopLoading]; didn't fix your issue. If this is the case and you make it into that if statement I suspect that something else is going on. Have you shared all your code? With this // Dismiss the view controller, continue loading the app, etc. in your code I suspect that you haven't shared everything in which case we can't help.

Answers 2

Check if there is anything for "UserAgent" in"standardUserDefaults". There are chances that UserAgent is getting appended in request URL. Or check for any "UserAgent" sent in url request.

Read More

Wednesday, April 26, 2017

OAuth Apps on a Single Domain

Leave a Comment

My company has a website. Let's pretend that it's hosted at http://www.example.com. I have three apps that I need to build for different teams. Users will have different permissions, possibly different OAuth logins, per app. I'd like to host apps on domains like:

  • http://www.example.com/apps/my-first-app
  • http://www.example.com/apps/my-second-app
  • http://www.example.com/apps/my-third-app

My question is can I do this? I'm trying to understand if OAuth tokens are per domain or per app/url. Thank you for your help.

2 Answers

Answers 1

OAuth Tokens are indeed per domain / app / url.

I did read a while back you can create multiple tokens and store those in the db for the time being so that multiple users with multiple roles can use those tokens to do the things they are permitted to in one domain for instance. I cannot really remember where I read it, but once I do i'll get back to you as soon as possible

Answers 2

You should be able to have multiple consumer apps like that. I'm not sure providers would work however.

Each consumer has a unique client ID and secret (and usually a callback url on the provider, github say). As long as each consumer application has a unique client ID I can't see why this wouldn't work - just create 3 applications on the provider and then make you set the callback urls correctly.

Read More

Friday, April 14, 2017

Advantages of using OAuth Password Credentials Grant over Token Access Authentication

Leave a Comment

I am creating an API for a mobile application using Rails 5. At the moment, I don't need three-legged authorization, as the API will only be consumed by our own mobile apps.

I'm thinking of choosing one of these two options:

  1. Doorkeeper + Devise: I can implement OAuth 2.0 using Doorkeeper, but I will only be using the Password Credentials Grant, at least for now.
  2. Rails' own ActionController::HttpAuthentication::Token module + Devise: This seems like the simpler way to go.

Honestly, I can't see the difference between the Token Access Authentication method and OAuth 2.0's Password Credentials Grant.

How would one choose one over the other? Is there any other option that needs to be considered?

2 Answers

Answers 1

If all you'll ever have is the "single purpose API" (only for mobile application), there is no big difference in terms of security.

But if you'd like to extend this API to be used by the external services, then, you'll be in a much better position with implemented OAuth 2.0 using Doorkeeper, because you can easily configure, for example, a Authorization Code Grant for them. So, I'd say that "Doorkeeper + Devise" option is more future-proof, because it provides more options, while HTTP Token authentication is much simpler for implementation.

Answers 2

The two are conceptually different things:

  • "Token Access Authentication" specifies a protocol describing how a (possibly long-lived) token should be presented to the server securely. It says nothing about where the token came from or how it should be interpreted.
  • "Password Credentials Grant" is a part of the fully-fledged OAuth flow, describing the means of obtaining a (usually short-lived) token.

In a sense, you could use Password Credentials Grant to obtain a token using OAuth and then use this token in the Token authorization header to gain access.

The question then becomes - is it useful to do the extra roundtrip for exchanging the (permanent and secret) credentials for a (temporary) token, when we could instead use the (permanent and secret) token stored in the app to authorize immediately anyway.

As I see it, there are two potential benefits of using the full OAuth flow. Firstly, it lets you add other means of authorization for third parties naturally. Secondly, it lets you revoke the token at any moment and force a re-authorization using these other means (if you implement them, of course) without having to invent any wheels.

On the other hand, you can always add any additional "token generation" parts later, when they are needed. Thus, if your current plan is to hard-code credentials in code anyway, I'd suspect you are probably better off relying on Token authorization.

Not only is it one request shorter, it may also be slightly more secure than the Bearer authentication used in OAuth: if an attacker sniffs a Bearer token, they would (usually) get full token access to the server until its expiration. It is not the case with Token tokens (normally). Not that it all matters too much of course if the attacker could extract the shared secret from your app anyway.

Read More

Friday, March 3, 2017

Should an oAuth server give the same accessToken to a same client request?

Leave a Comment

I am developing an oAuth2 server and I've stumbled upon this question.

Lets suppose a scenario where my tokens are set to expire within one hour. On this timeframe, some client goes through the implicit auth fifty times using the same client_id and same redirect_uri. Basically same everything.

Should I give it the same accessToken generated on the first request on the subsequent ones until it expires or should I issue a new accessToken on every request?

The benefits of sending the same token is that I won't leave stale and unused tokens of a client on the server, minimizing the window for an attacker trying to guess a valid token.

I know that I should rate-limit things and I am doing it, but in the case of a large botnet attack from thousands of different machines, some limits won't take effect immediately.

However, I am not sure about the downsides of this solution and that's why I came here. Is it a valid solution?

4 Answers

Answers 1

I would rather say - no.

Reasons:

  1. You should NEVER store access tokens in plain text on the Authorization Server side. Access tokens are credentials and should be stored hashed. Salting might not be necessary since they are generated strings anyway. See OAuth RFC point 10.3.
  2. Depending how you handle subsequent requests - an attacker who knows that a certain resource owner is using your service and repeat requests for the used client id. That way an attacker will be able to impersonate the resource owner. If you really return the same token then at least ensure that you authenticate the resource owner every time.
  3. What about the "state" parameter? Will you consider requests to be the "same" if the state parameter is different? If no then a botnet attack will simply use a different state every time and force you to issue new tokens.

As an addition - generally defending against a botnet attack via application logic is very hard. The server exposing your AS to the internet should take care for that. On application layer you should take care that it does not go down from small-bandwidth attacks.

Answers 2

You can return the same access_token if it is still valid, there's no issue with that. The only downside may be in the fact that you use the Implicit flow and thus repeatedly send the - same, valid - access token in a URL fragment which is considered less secure than using e.g. the Authorization Code flow.

Answers 3

As a thumb rule never reuse keys, this will bring additional security in the designed system in case of key capture

Answers 4

You can send different access token when requested after proper authentication and also send refresh token along your access token.

Once your access token expires, you should inform user about that and user should re-request for new access token providing one-time-use refresh token previously provided to them skipping need for re-authentication, and you should provide new access token and refresh token.

To resist attack with fake refresh token, you should blacklist them along with their originating IP after few warnings.

PS: Never use predictable tokens. Atleast make it extremely difficult to brute force attacks by using totally random, long alpha-numeric strings. I would suggest bin2hex(openssl_random_pseudo_bytes(512)), if you are using php.

Read More

Wednesday, February 8, 2017

Server-side Google Sign-In, way to encrypt/decrypt data with Google-managed secrets?

Leave a Comment

It's rather straightforward to use the Google Sign-In library on the server side and attain a GoogleIdToken to validate a user's identity. However, I'd like to encrypt per-user data in my database with a secret that's unique to every user. Is there an easy way to do this? If not using Google Sign-in, you can derive keys from a user's password, but that's obviously not possible here.

3 Answers

Answers 1

Well, first of all, you're drawing a parallel to using the user's password to derive an encryption key, but since you're talking about that as an alternative if you weren't using Google Sign-On, that implies your talking about using the password that users would authenticate with. That's a bad idea.

Users need to be able to change their authentication password, and that will be a major hassle for you if you're encrypting with it. It will require you to decrypt everything with the old password and then re-encrypt it with the new one.

So what you need to find is something that you can pull out of the GoogleIdToken that will never change. Email addresses change, so I wouldn't use that. Perhaps the user id, which you can get with GoogleIdToken.getPayload().getSubject() is what you want. Then what you would want to do is derive a key from that. I would look for ways to combine it with other information that the user gives you that really is secret, though.

Answers 2

I really don't know anything about this, so I'm kinda just thinking out loud.

To get some idea as to the general process for using Google Sign In I've been looking over the following guides found at the Google Sign-in for Websites page

  • Integrate Google Sign-In
  • Authenticate with a Backend Server
  • Google Sign-In for Server-Side Apps

Anyway, it seemes like it should be possible to use some combination of immutable characteristics of the users GoogleIdToken like their email, user id, etc in combination with some immutable characteristics of your app or web site, such as the app id or some other secret and create a hash value from that. Use that as your encryption key, or maybe send that thru OpenSSH or something for a stronger encryption hash.

Seems like in interesting problem, wish I had some insight into solving it. Perhaps I will research this more as I have a few interesting side projects I'm tinkering on.

Answers 3

The information you receive during a Google sign on is intended for authentication purposes. The id token is encoded as a Json Web Token. There is nothing secret in a JWT.

The information is cryptographically signed by the authentication provider, so you can verify the information. This is of no help for deriving secrets, though.

Looks like you'll have to find another way.

Read More