GithubHelp home page GithubHelp logo

oktadev / spring-boot-microservices-example Goto Github PK

View Code? Open in Web Editor NEW
323.0 15.0 150.0 6.58 MB

Bootiful Microservices with Spring Boot

Home Page: https://developer.okta.com/blog/2017/06/15/build-microservices-architecture-spring-boot

License: Apache License 2.0

Shell 11.58% Java 26.04% TypeScript 46.45% JavaScript 8.16% HTML 6.81% CSS 0.95%
spring-boot spring-cloud spring-cloud-netflix eureka-server hystrix feign

spring-boot-microservices-example's Introduction

Bootiful Microservices with Spring Boot

This example shows how to create a microservices architecture with Spring Boot and display its data with an Angular UI.

Please read Build a Microservices Architecture for Microbrews with Spring Boot for a tutorial that shows you how to build this application.

Prerequisites: Java 8 and Node.js.

Okta has Authentication and User Management APIs that reduce development time with instant-on, scalable user infrastructure. Okta's intuitive API and expert support make it easy for developers to authenticate, manage and secure users and roles in any application.

Getting Started

To install this example application, run the following commands:

git clone https://github.com/oktadeveloper/spring-boot-microservices-example.git
cd spring-boot-microservices-example

This will get a copy of the project installed locally. To run the client and all the servers, execute ./run.sh, or execute the commands in this file manually.

r=`pwd`
echo $r

# Eureka
cd $r/eureka-service
echo "Starting Eureka Service..."
mvn -q clean spring-boot:run &

# Beer Service
echo "Starting Beer Catalog Service..."
cd $r/beer-catalog-service
mvn -q clean spring-boot:run &

# Edge Service
echo "Starting Edge Service..."
cd $r/edge-service
mvn -q clean spring-boot:run &

# Client
cd $r/client
npm install
echo "Starting Angular Client..."
npm start

The primary example (without authentication) is in the master branch. A pure Spring Security OAuth implementation is in an oauth branch, and an example with the Stormpath SDK is in the okta branch. Both branches use the Okta Sign-In Widget on the front end.

Spring Security OAuth

Okta implements the OAuth 2.0 protocol for its API. This means you can use libraries like Spring Security OAuth to provide single sign-on to your applications.

To check out the branch that uses Spring Security OAuth, run the following command.

git checkout oauth

The code in the oauth branch is described in Secure a Spring Microservices Architecture with Spring Security and OAuth 2.0.

The changes required to move from the Stormpath SDK to Spring Security OAuth can be viewed in pull request #8.

Create Applications in Okta

If you don't have one, create an Okta Developer account. After you've completed the setup process, log in to your account and navigate to Applications > Add Application. Click Web and Next. On the next page, enter the following values and click Done.

  • Application Name: Spring OAuth
  • Base URIs: http://localhost:8081
  • Login redirect URIs: http://localhost:8081/login

You need to add a roles claim to your ID Token, so your groups in Okta are translated to Spring Security authorities. In your Okta developer console, navigate to API > Authorization Servers, click the Authorization Servers tab and edit the default one. Click the Claims tab and Add Claim. Name it "roles" and include it in the ID Token. Set the value type to "Groups" and set the filter to be a Regex of .*.

Change security.oauth2.* properties in the following files to enter your client ID and client secret.

You can also create a ~/.okta.env file to override the properties in these files.

#!/bin/bash

# Okta with JHipster
export SECURITY_OAUTH2_CLIENT_ACCESS_TOKEN_URI="https://{yourOktaDomain}.com/oauth2/default/v1/token"
export SECURITY_OAUTH2_CLIENT_USER_AUTHORIZATION_URI="https://{yourOktaDomain}.com/oauth2/default/v1/authorize"
export SECURITY_OAUTH2_RESOURCE_USER_INFO_URI="https://{yourOktaDomain}.com/oauth2/default/v1/userinfo"
export SECURITY_OAUTH2_RESOURCE_TOKEN_INFO_URI="https://{yourOktaDomain}.com/oauth2/default/v1/introspect"
export SECURITY_OAUTH2_CLIENT_CLIENT_ID="{clientId}"
export SECURITY_OAUTH2_CLIENT_CLIENT_SECRET="{clientSecret}"

Then run the following before starting any servers.

source ~/.okta.env

To use Okta's Sign-In Widget, you'll need to modify your app in Okta to enable an Implicit grant type. Log in to your account, navigate to Applications > Spring OAuth > General tab and click Edit. Enable Implicit (Hybrid) under Allowed grant types and select both checkboxes below it. Add http://localhost:4200 under Login redirect URIs and click Save.

In order for the Sign-In Widget to make requests to this application, you'll also need to configure the client URL as a trusted origin. Click API > Trusted Origins > Add Origin. Enter http://localhost:4200 as the Origin URL and select both checkboxes under it.

Change {clientId} and {yourOktaDomain} in client/src/app/shared/okta/okta.service.ts to match your app's values.

signIn = new OktaSignIn({
  baseUrl: 'https://{yourOktaDomain}.com',
  clientId: '{clientId}',
  authParams: {
    issuer: 'default',
    responseType: ['id_token', 'token'],
    scopes: ['openid', 'email', 'profile']
  }
});

Stormpath SDK

To check out the branch that uses the Stormpath SDK, run the following command.

git checkout okta

The code in the okta branch is described in Secure a Spring Microservices Architecture with Spring Security, JWTs, Juiser, and Okta.

Create Applications in Okta

You will need to create an Okta developer account to configure the Spring Boot side of things. After creating an app and an access token, you should be able to set the following environment variables:

export STORMPATH_CLIENT_BASEURL={baseUrl}
export OKTA_APPLICATION_ID={applicationId}
export OKTA_API_TOKEN={apiToken}
export OKTA_AUTHORIZATIONSERVER_ID=default

After you set these environment variables, make sure to restart your Spring Boot applications.

For Angular, you'll need to create an OIDC app on Okta. Change {clientId} and {yourOktaDomain} in client/src/app/shared/okta/okta.service.ts to match your app's values.

signIn = new OktaSignIn({
  baseUrl: 'https://{yourOktaDomain}.com',
  clientId: '{clientId}',
  authParams: {
    issuer: 'default',
    responseType: ['id_token', 'token'],
    scopes: ['openid', 'email', 'profile']
  }
});

NOTE: The value of {yourOktaDomain} should be something like dev-123456.oktapreview.com. Make sure you don't include -admin in the value!

After making these changes, you should be able to log in with your credentials at http://localhost:4200.

Links

This example uses the following libraries provided by Okta:

Help

Please post any questions as comments on the following blog posts, or visit our Okta Developer Forums. You can also email [email protected] if would like to create a support ticket.

License

Apache 2.0, see LICENSE.

spring-boot-microservices-example's People

Contributors

dependabot[bot] avatar imgbot[bot] avatar joshlong avatar mraible 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  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

spring-boot-microservices-example's Issues

No default constructor for entity

When Iam trying to start the beer-catalog-service, I keep getting this below error. Would appreciate your help on this.

2018-04-13 18:06:20.415 ERROR 25728 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:800) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:781) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:335) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at com.example.beercatalogservice.BeerCatalogServiceApplication.main(BeerCatalogServiceApplication.java:25) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_162]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_162]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_162]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_162]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.1.RELEASE.jar:2.0.1.RELEASE]
Caused by: org.springframework.orm.jpa.JpaSystemException: No default constructor for entity: : com.example.beercatalogservice.Beer; nested exception is org.hibernate.InstantiationException: No default constructor for entity: : com.example.beercatalogservice.Beer
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:314) ~[spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:225) ~[spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527) ~[spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) ~[spring-tx-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153) ~[spring-tx-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135) ~[spring-data-jpa-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61) ~[spring-data-commons-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at com.example.beercatalogservice.$Proxy122.findAll(Unknown Source) ~[na:na]
at com.example.beercatalogservice.BeerInitializer.run(BeerCatalogServiceApplication.java:67) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:797) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
... 10 common frames omitted
Caused by: org.hibernate.InstantiationException: No default constructor for entity: : com.example.beercatalogservice.Beer
at org.hibernate.tuple.PojoInstantiator.instantiate(PojoInstantiator.java:85) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tuple.PojoInstantiator.instantiate(PojoInstantiator.java:105) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tuple.entity.AbstractEntityTuplizer.instantiate(AbstractEntityTuplizer.java:673) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.instantiate(AbstractEntityPersister.java:4774) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.internal.SessionImpl.instantiate(SessionImpl.java:1625) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.internal.SessionImpl.instantiate(SessionImpl.java:1609) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1664) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.loader.Loader.getRow(Loader.java:1562) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:732) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.loader.Loader.processResultSet(Loader.java:991) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]

Edge service is not starting - BindException

Run eureka-service http://localhost:8761 - started
Run beer-catalog-service http://localhost:8080/beers - could able to see the list
Run edge-service ; Iam not able to start the edge-service, seeing the below exception. Here, Iam using port 8082.
Any help would be appreciated.

2018-04-17 17:29:34.284 INFO 812 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_EDGE-SERVICE/HFFF014134.us:edge-service: registering service...
2018-04-17 17:29:34.310 ERROR 812 --- [ main] o.apache.catalina.core.StandardService : Failed to start connector [Connector[HTTP/1.1-8080]]

org.apache.catalina.LifecycleException: Failed to start component [Connector[HTTP/1.1-8080]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167) ~[tomcat-embed-core-8.5.29.jar:8.5.29]

at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at com.example.edgeservice.EdgeServiceApplication.main(EdgeServiceApplication.java:29) [classes/:na]

Caused by: org.apache.catalina.LifecycleException: Protocol handler start failed
at org.apache.catalina.connector.Connector.startInternal(Connector.java:1020) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
... 13 common frames omitted
Caused by: java.net.BindException: Address already in use: bind
at sun.nio.ch.Net.bind0(Native Method) ~[na:1.8.0_162]
at org.apache.coyote.AbstractProtocol.start(AbstractProtocol.java:591) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at org.apache.catalina.connector.Connector.startInternal(Connector.java:1018) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
... 14 common frames omitted

2018-04-17 17:29:34.321 INFO 812 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-04-17 17:29:34.327 WARN 812 --- [ost-startStop-1] o.a.c.loader.WebappClassLoaderBase : The web application [ROOT] appears to have started a thread named [spring.cloud.inetutils] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
sun.misc.Unsafe.park(Native Method)

2018-04-17 17:29:34.434 INFO 812 --- [ main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-04-17 17:29:34.437 ERROR 812 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :


APPLICATION FAILED TO START


Description:

The Tomcat connector configured to listen on port 8080 failed to start. The port may already be in use or the connector may be misconfigured.

Action:

Verify the connector's configuration, identify and stop any process that's listening on port 8080, or configure this application to listen on another port.

Unable to use this `oauth` branch

I've been unable to use the code in the oauth branch without adjustment. I was receiving an error with a page

<oauth>
  <error_description> Invalid token does not contain resource id (oauth2-resource</error_description>
  <error>access_denied</error> 
</oauth>

I fixed it by setting the resourceId explicitly in the code, using a value I put in application.properties. Submitted a PR with my code, not sure if there's a better way to do it, but it's how I got it working.

OAUTH_ERROR: 'redirect_uri' parameter

I'm encountering problems during login (http://localhost:4200), where I get the following error: "OAUTH_ERROR: The 'redirect_uri' parameter must be an absolute URI that is whitelisted in the client app settings." The result is an endlessly spinning wheel on the login page.

The following is a screenshot of what I see.

screen shot 2017-11-27 at 11 33 57 pm

I'm not entirely sure where I need to whitelist the URI. Any ideas?

springboot microservices gatewayservice routing issue

Environment Detail:
spring boot version 2.6.6
spring-cloud-gateway-server 3.1.1.jar

Configuration in application.properties:
spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true

Port Detail:
ProductGatewayService: 5069
PssTitleService: 5071

With the above set up If I am invoking the below url I am getting proper response.
http://localhost:5069/psstitleservice/api/productService/getTitleData - working fine

In actual scenario: I am having a context path with my gateway service. /cmdgservices
With the context path, I have tried many things but none of the below way is working.

Way 1 :
spring.cloud.gateway.discovery.locator.predicates[0].name: Path
spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]: "'/'+psstitleservice+'/**'"

Way 2 :
spring.cloud.gateway.discovery.locator.predicates[0].name: Path
spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]: "'cmdgservices/'+psstitleservice+'/**'"

Way 3 :
spring.cloud.gateway.discovery.locator.predicates[0].name: Path
spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]: "'cmdgservices/'+psstitleservice+'/**'"
spring.cloud.gateway.discovery.locator.url-expression: 'lb://'+psstitleservice

Way 4 (In Java configuration):
@configuration
public class ApiGatewayConfiguration {
@bean
public RouteLocator gatewayRouter(RouteLocatorBuilder builder) {
return builder.routes()
.route("test_route", p -> p.path("/psstitleservice")
.uri("http://localhost:5071"))
.build();
}

I have already invested 3 days behind it. I would be grateful to any helping hand. Thanks in advance.

Fails to implement the OAUTH branch.

Hi,

I have tried to test the OAUTH branch by using this document. After running the ./run.sh command, all the application is up and running.

Screenshot (511)

When I tried to access https//localhost:8081/good-beers an OKTA sign-in page popped up. After successful login, I can see a list of good-beers.

But when I tried to access https://localhost:8081/home ,it gave me the error "Invalid token does not contain resource id (oauth2-resource)"

Screenshot (512)

Can you please provide me with some pointers here?

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.