Giter VIP home page Giter VIP logo

auth0-spring-security5-api-sample's Introduction

Auth0 Spring Security API Samples

CircleCI

These samples demonstrate how to create an API with Spring Boot and the Okta Spring Boot Starter.

These samples do not demonstrate how to sign a JWT but rather assume that a user has already been authenticated by Auth0 and holds an access token for API access. For information on how to use Auth0 to authenticate users, see the docs.

What is Auth0?

Auth0 helps you to:

  • Add authentication with multiple authentication sources, either social like Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, amont others, or enterprise identity systems like Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider.
  • Add authentication through more traditional username/password databases.
  • Add support for linking different user accounts with the same user.
  • Support for generating signed Json Web Tokens to call your APIs and flow the user identity securely.
  • Analytics of how, when and where users are logging in.
  • Pull data from other sources and add it to the user profile, through JavaScript rules.

Create a free Auth0 account

  1. Go to Auth0 and click Sign Up.
  2. Use Google, GitHub or Microsoft Account to login.

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

Author

Auth0

License

This project is licensed under the MIT license. See the LICENSE file for more info.

auth0-spring-security5-api-sample's People

Contributors

dependabot[bot] avatar evansims avatar jimmyjames avatar joshcanhelp avatar lbalmaceda avatar omar-compres avatar poovamraj avatar sergiught avatar widcket avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

auth0-spring-security5-api-sample's Issues

Does not work with spring > 3

I had a working setup.

I upgraded spring-boot-starter-parent from 2.7.1 to 3.0.2.
Because of that some imports changed from javax.servlet to jacarta.servlet
In the SecurityFilterChain the authz.antMatchers(HttpMethod.GET, "/api/v1/hero") call changed to
authz.requestMatchers(HttpMethod.GET, "/api/v1/hero")

Now I get 404 for both get and post for the url. (Wait, before that POST to that url was working as well, and it did need authentication and csrf... So there is something not really right in the config...)

The diff between the nonworking and working setup is here: https://gist.github.com/magwas/53d4cfcb7769d9f7f5ef5978fa121bf9

My full SecurityConfig (new version):

package com.kodekonveyor;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

import com.kodekonveyor.annotations.InterfaceClass;

@InterfaceClass
@EnableWebSecurity
public class SecurityConfig {

	@Value("${auth0.audience}")
	private String audience;

	@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
	private String issuer;

	@Autowired
	Logger logger;

	@Bean
	public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
		http
				.authorizeHttpRequests(
						authz -> authz
								.requestMatchers(HttpMethod.GET, "/api/v1/hero")
								.hasAuthority("SCOPE_read:current_user")
								.anyRequest().permitAll())
				.oauth2ResourceServer(oauth2 -> oauth2.jwt())
				.csrf()
				.csrfTokenRepository(
						CookieCsrfTokenRepository.withHttpOnlyFalse());

		return http.build();

	}
}

401 Unauthorized on POST endpoint in Spring Boot (MVC) application

Hi, I am using Spring Boot 3 and Spring Security 6 and following the sample https://github.com/auth0-samples/auth0-spring-security5-api-sample/tree/use-spring-6/01-Authorization-MVC. Tutorial works well until I try with GET endpoints. But the moment I built a POST endpoint and call it, I get 401 Unauthorized error in postman even though this is configured to be permitted in SecurityConfig.java. Here is the link to my code changes https://github.com/ashishrky/auth0-spring-security5-api-sample/commit/8bf9866a7a18fb9d2e0c78f1950725f2f42eaee2. What’s wrong? Why GET call work just fine, but POST call get 401?

Posted in Auth0 community as well at https://community.auth0.com/t/401-unauthorized-on-post-endpoint-in-spring-boot-mvc-application/103716

Custom jwtDecoder not configured

Hi

I think the custom jwtDecoder decoder is not configured.

Shouldn't it be configured in SecurityConfig.java like this?

    http.authorizeRequests()
            .mvcMatchers("/api/public").permitAll()
            .mvcMatchers("/api/private*").authenticated()
            .and().cors()
            .and().oauth2ResourceServer()
            .jwt(jwt -> jwt.decoder(jwtDecoder()));
    return http.build();

Deprecated example, All of the site is protected, not just the API.

The following had some problems:

http.authorizeRequests()
                .mvcMatchers("/api/public").permitAll()
                .mvcMatchers("/api/private").authenticated()
                .mvcMatchers("/api/private-scoped").hasAuthority("SCOPE_read:messages")
                .and().cors()
                .and().oauth2ResourceServer().jwt();

authorizeRequests is deprecated,
mvcMatchers is undefined.

Relevant parts of pom.xml:

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.0.2</version>
	</parent>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>

Now my SecurityConfig looks like below. No kidding. jwtDecoder commented out, and all-permitting filterchain. I even deleted AudienceValidator. I am running the server with jetty. All of the urls are 401 by default, and work as expected if I add the Authorization header as described here: https://auth0.com/docs/quickstart/backend/java-spring-security5/02-using

I could have code or config left from earlier tries, however I made every effort not to, and triple-checked all places suspect. (everything WEB-INF or resources, files ending in xml)

package com.kodekonveyor;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
public class SecurityConfig {

	@Value("${auth0.audience}")
	private String audience;

	@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
	private String issuer;

	@Autowired
	Logger logger;

	/*
		@Bean
		JwtDecoder jwtDecoder() {
			logger.info("jwtDecoder");
			NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder) JwtDecoders
					.fromOidcIssuerLocation(issuer);
	
			OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(
					audience);
			OAuth2TokenValidator<Jwt> withIssuer = JwtValidators
					.createDefaultWithIssuer(issuer);
			OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(
					withIssuer, audienceValidator);
	
			jwtDecoder.setJwtValidator(withAudience);
	
			return jwtDecoder;
		}
	*/
	@Bean
	public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
		http.authorizeHttpRequests().anyRequest().permitAll();
		/*
		http.authorizeHttpRequests()
				.requestMatchers("/api/**").permitAll();
		  .requestMatchers("/private").
		  hasAuthority(
		  "SCOPE_read:messages")
		  .and().cors()
		  .and().oauth2ResourceServer()
		  .jwt();
		 */
		return http.build();

	}
}

Spring Boot 3 and Spring Security 6

For those using or upgrading to Spring Boot 3 with Spring Security 6, we will be either creating a new sample repo and corresponding quickstart article, or updating this sample and the existing quickstart. In the meantime, let's use this issue to discuss any issues and share tips that may help others.

Trying the upgrade to Spring Boot 3 myself, these are my findings which I hope will others:

Note
The WIP changes can be found on the use-spring-6 branch.

Migrating to Spring Boot 3 and Spring Security 6 (Servlet)

Step 1 - Update to latest Spring Boot 3 and Spring Security 5.8

Note
The following changes are captured in this commit.

As documented on the Spring Boot 3 Migration Guide, the first thing to do is update to the latest of Spring Boot 2 and use Spring Security 5.8. As shown in this commit, this involves updating your dependencies (gradle shown):

plugins {
    latest 
    id 'org.springframework.boot' version '2.7.8'
}

ext['spring-security.version']='5.8.1'

After doing this, you'll notice deprecation warnings regarding the authorizeRequests and mvcMatchers usage in the SecurityConfig. We can change this to use authorizeHttpRequests and use requestMatcher:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
            .authorizeHttpRequests((authorize) -> authorize
                .requestMatchers("/api/public").permitAll()
                .requestMatchers("/api/private").authenticated()
                .requestMatchers("/api/private-scoped").hasAuthority("SCOPE_read:messages"))
              .cors().and()
              .oauth2ResourceServer((oauth2ResourceServer) ->
                      // works, but not as clear:
                      // oauth2ResourceServer.jwt());
                      oauth2ResourceServer.jwt(jwt -> jwt.decoder(jwtDecoder())));

    return http.build();
}

The application should now compile without warnings, and running it should demonstrate the protected endpoints.

Step 2 - Update to Spring Boot 3

Note
The following changes are captured in this commit.

Now we can update to Spring Boot 3, which involves a few things:

Update to latest Gradle

Update your gradle version to the latest of v7. If you don't do this, you may encounter errors related to building a jar when trying to run.

./gradlew wrapper --gradle-version 7.6

Update dependencies and source level

Update your dependency to use spring boot 3 (and make sure to remove the Spring Security version override if you followed the step above!):

plugins {
    // ...
    id 'org.springframework.boot' version '3.0.2'
}

sourceCompatibility = '17'

Add @Configuration annotation to SecurityConfig

Make sure to add the @Configuration annotation to the SecurityConfig class. Not doing this will cause the custom jwtDecoder bean to not get injected (the annotation should probably have always been there, but something in Spring Boot 3 seems to have made it required).

@EnableWebSecurity

// Needed since Spring Security 6 (or Spring Boot 3)!
@Configuration
public class SecurityConfig {
   //...
}

Run with Java 17!

If you followed the above steps, you should be able to run the sample. Note that Spring Boot 3 requires Java 17, and the application will fail to start if using a non-compatible java runtime.

./gradlew clean bootRun

Migrating to Spring Boot 3 and Spring Security 6 (WebFlux)

Note
The required updates for this sample can be found in this commit.

Updating the WebFlux usage for Spring Boot 3 appears to be a bit simpler, requiring the following:

  • Update spring boot dependency to latest spring boot v3
  • Update to latest Gradle
  • Configure source compatibility to level 17
  • Add the @Configuration annotation to the SecurityConfig class

After doing the above, you should be able to run the application using a Java 17 runtime and see that the APIs are protected based on their authorization requirements.

Built-in audience check

Hi there! Are there any benefits to using a custom AudienceValidator vs using the built-in property?

spring-projects/spring-boot#29084

Just wanted to check before moving forward with our integration - I don't think there is a difference functionally but wanted to check the Auth0 team's advice. Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.