Secure a Spring Boot App (Okta, oAuth 2.0,OpenID
connect integrated) with Spring Security and PreAuthorize.
In this post we will
secure our restAPI with Okta’s user authentication and authorization. There are
two ways to hook Authentication and Authorization in SpringBoot. The first way
focuses on overriding the original setting on the HttpSecurity object by building WebSecurityConfigurerAdapter
and the second method is using @PreAuthorize
annotation on
controller method.
If access is not granted,
the method is not executed, and an HTTP Unauthorized is returned. In practice,
using the @PreAuthorizeannotation on a controller method is very
similar to using HttpSecurity pattern matchers on a specific
endpoint.
1.
Start
a Sample Project Using Spring Initializr
1.1 POM Dependencies
1.2 Exposing RESTApi
@RestController
public class HomeController {
@PreAuthorize("hasAuthority('Admin')")
@RequestMapping("/restricted")
@ResponseBody
public String restricted() {
return "Only for Admin!";
}
@PreAuthorize("hasAuthority('User')")
@RequestMapping("/user")
@ResponseBody
public String user() {
return "Only for user!";
}
}
Here two apis are exposed one is /restricted with Admin rights and another is /user for User rights.
1.3 Security Configuration
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(final HttpSecurity http) throws Exception {
http.antMatcher("/**")
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and().oauth2Login(); // <--
THIS WAS CHANGED
}
}
Make sure to use oauth2Login() option.
The @EnableGlobalMethodSecurity(prePostEnabled = true) annotation is what enables the @PreAuthorize annotation.
OAuth 2.0 is an industry-standard authorization
protocol, and OIDC is another open standard on top of OAuth that adds an
identity layer (authentication). Together they provide a structured way for
programs to manage authentication and authorization and to communicate across
networks and the internet.
Neither OAuth nor OIDC, however, provide an implementation. They are just specs or protocols. That’s where Okta comes in. Okta has an implementation of the OAuth 2.0 and OIDC specs that allows for programs to use their services to quickly provide login, registration, and single sign-on (or social login) services.
2. Okta account setup
First, sign up for a free Okta Developer account: https://developer.okta.com/signup/
From your Okta developer dashboard, in the top menu, click on Applications.
- Click the green Add Application button.
- Click Web application type,
and Next.
- Give the app a Name. Any name.
- Set Login Redirect URIs to http://localhost:8080/login/oauth2/code/okta
- Click Done.
Take note of the Client ID and Client Secret and configure in you applications
application.properties file as mentioned below.
3. Activate Groups Claim on Okta
Okta doesn’t by default include
the groups claim in the JSON Web Token (JWT). The JWT is what Okta uses to
communicate authentication and authorization information to the client app. A
deeper dive into that is available in some other blog posts linked to at the
end of this one.
To configure Okta to add
the groups claim, go to your Okta developer dashboard.
From the top menu, go to API and
select Authorization Servers.
Select the default authorization
server.
Click on the Claims tab.
Click on Add claim
First, add a claim mapping for token
type Access Token.
Click Add Claim.
Update the following values (the
other default values are fine):
- Name: groups
- Include
in token type:
Access Token
- Value
type: Groups
- Filter: Matches regex, .*
Second, add a second claim mapping
for token type ID Token.
Click Add Claim.
Update the following values (just the
same as above except token type):
- Name: groups
- Include
in token type: ID Token
- Value
type: Groups
- Filter: Matches
regex, .*
Now, you want to add an Admin group
on Okta. Log into your Okta developer dashboard.
From the top menu, go to Users and
select Groups.
Click Add Group.
In the popup:
- Name the
group “Admin”
- Description can
be whatever you like
- Click Add
Group
Now, you want to add an User group
on Okta. Log into your Okta developer dashboard.
From the top menu, go to Users and
select Groups.
Click Add Group.
In the popup:
- Name the
group “User”
- Description can
be whatever you like
- Click Add
Group
Add Your User To the Admin and User Group
Till now you have created two group
Admin and User with respected users.
5. Add
your groups to Application
Go
to Applications tab and click you application
Go
to Assignments tab and click on Assign green button and click Assign to Groups
from the drop down.
Add
required groups, I have added Admin and User group.
Till
now OKTA setup is done with two Groups(Admin and User), now start your
application and try to access the /restricted api with user who is part of User
group.
Since we do not have specific error
page, it is showing default error page.
Now access /restricted api with Admin
group user
Recap
We configured Spring Boot to use Okta as an OAuth 2.0 / OIDC single sign-on provider and added a groups claim to the authentication server and the client app. You even a new Admin group and saw how to use the groups claim, mapped to a Spring authority, to restrict access. Finally, you took a look at how OAuth 2.0 scopes can be used to define authorization schemes and implement them in the app.