LoginSignup

(一)Trend
(二)Qiita Engineer Festa 2024
(三)Question
(四)Official Event
(五)Official Column
(六)Career
(七)Organization
 



33
Go to list of users who liked
33








More than 5 years have passed since last update.

@AkihiroTakamura

SpringBootSpring Security OAuth2OAuth

OAuth
spring-security
SpringBoot
Last updated at Posted at 2016-02-18

使



Eclipse

Gradle



install



Eclipse Market Place

Gradle IDE Pack

Spring Tool Suite



Project setup

project



Eclipse - File - New - Project...

Gradle - Gradle Project

Project nameSample ProjectJava Quick start


Kobito.7FuXjY.png



src/main/java 

src/main/resources 

src/test/java 

src/test/resources 



gradle



package versionprojectgradle.properties



gradle.properties

SPRING_BOOT_VERSION=1.3.2.RELEASE
SPRING_LOADED_VERSION=1.2.5.RELEASE
JAVA_VERSION=1.8
POSTGRES_VERSION=9.4-1200-jdbc41
SPRING_CORE_VERSION=4.2.4.RELEASE




build.gradle



build.gradle

buildscript {
    repositories {
      mavenCentral()
      maven {
        url "https://plugins.gradle.org/m2/"
      }
    }
    dependencies {
      classpath "org.springframework.boot:spring-boot-gradle-plugin:${SPRING_BOOT_VERSION}"
      classpath "org.springframework:springloaded:${SPRING_LOADED_VERSION}"
    }
}

apply plugin: 'java'
apply plugin: 'spring-boot'

sourceCompatibility = "${JAVA_VERSION}"
targetCompatibility = "${JAVA_VERSION}"

repositories {
  mavenCentral()
}

jar.baseName = 'springboot-oauth-sample'

dependencies {
    // for web application
    compile "org.springframework.boot:spring-boot-starter-web:${SPRING_BOOT_VERSION}"

    // template engine: jade
    compile "com.domingosuarez.boot:spring-boot-starter-jade4j:0.3.0"

    // use spring security
    compile "org.springframework.boot:spring-boot-starter-security:${SPRING_BOOT_VERSION}"

    // use spring security oauth2
    compile "org.springframework.security.oauth:spring-security-oauth2:2.0.7.RELEASE"

    // use configuration processor
    compile "org.springframework.boot:spring-boot-configuration-processor:1.2.5.RELEASE"

    // use spring core
    compile "org.springframework:spring-core:${SPRING_CORE_VERSION}"

    // use Scribe OAuth
    compile "com.github.scribejava:scribejava-apis:2.2.2"

}





Project - Gradle - Refresh All

coding



src/main/java - New - Package



package namespringboot.oauth.sample



 - New - Class - Main.java


package springboot.oauth.sample;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Main {

  public static void main(String[] args)  {
    SpringApplication.run(Main.class, args);
  }

}


application



src/main/resources/application.yml

oauth serverclient

client-idclient-secret

oauth serverurl



OAuth


server:
  port: 8080
  session-timeout: 1200

spring:
  main:  
    show-banner: true

security:
  basic:
    enabled: false
  oauth2:
    client:
      client-id: sampleapp
      client-secret: wlpaBFBJTzmRLcLInQcIiS8ggLclLjQg
      access-token-uri: http://localhost:9999/api/oauth2/token
      user-authorization-uri: http://localhost:9999/api/oauth2/authorize
      scope: admin,user
      authorized-grant-types: authorization_code,refresh_token,client_credentials

    resource:
      user-info-uri: http://localhost:9999/api/profile
      prefer-token-info: false

    custom:
      # for single sign out(global logout)
      server-logout-url: http://localhost:9999/logout

      # redirect url for after single signed out
      server-logouted-redirect-url: http://localhost:8080/



Spring security



src/main/java//config/SecurityConfig.java

spring securityurl

HttpSecurity



spring securityOAuth@EnableOAuth2Sso


package springboot.oauth.sample.config;

import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter.XFrameOptionsMode;

@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Value("${security.oauth2.custom.server-logout-url}") private String serverLogoutUrl;

  @Value("${security.oauth2.custom.server-logouted-redirect-url}") private String serverLogoutedRedirectUrl;

  @Override
  public void configure(HttpSecurity http) throws Exception {
    http
      .headers()
        // allow iframe
        .addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN))
      .and()
      .authorizeRequests()
      .antMatchers("/public/**").permitAll()
      .antMatchers("/").permitAll()
      .antMatchers("/admin/**").hasRole("ADMIN")
      .anyRequest().authenticated()
      .and()
      .csrf()
        .csrfTokenRepository(csrfTokenRepository())
      .and()
      .logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl(serverLogoutUrl + "?next=" + serverLogoutedRedirectUrl)
        .deleteCookies("JSESSIONID")
        .invalidateHttpSession(true)
        .permitAll()
    ;
  }

  private CsrfTokenRepository csrfTokenRepository() {
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
    repository.setHeaderName("X-XSRF-TOKEN");
    return repository;
  }
}


Controller




URL


SecurityConfig.javaURL

/protected



OAuthOKaccessTokenprofile

OKcontrollerOAuth2Authentication



package springboot.oauth.sample.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/protected")
public class ProtectedController extends BaseController {

  @RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
  public Authentication index(OAuth2Authentication authentication) {
    return authentication;
  }
}




localhost:8080/protected

OAuth


Kobito.Q01sVF.png

OKSpring Security

/loginURL使OAuth code

code使OAuthaccess_token

access_token使OAuthprofile apiprofile

URL




Kobito.1bghvM.png



localhost:8080/logout

/logoutSecurityConfigURLspring securityurl



OAuthURLOAuth

global logout





33
Go to list of users who liked
33
0
Go to list of comments
Register as a new user and use Qiita more conveniently
(一)You get articles that match your needs
(二)You can efficiently read back useful information
(三)You can use dark theme
What you can do with signing up
Sign upLogin


33
Go to list of users who liked
33

 


How developers code is here.
© 2011-2024Qiita Inc.

Guide & Help
About
Terms
Privacy
Guideline
Design Guideline
Feedback
Help
Advertisement
Contents
Release Note
Official Event
Official Column
Advent Calendar
Qiita Award
API
Career
SNS
X(Twitter)@Qiita
X(Twitter)@qiita_milestone
X(Twitter)@qiitapoi
Facebook@Qiita
Our service
Qiita Team
Qiita Zine
Official Shop
Company
About Us
Careers
Qiita Blog