spring-boot

48行で Login して User とる

謎にハマってしまって結構調べた。。。次に何かのネタに。。。

package com.example;

import java.net.URI;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.Value;
import lombok.extern.slf4j.Slf4j;

@SpringBootApplication
@EnableOAuth2Sso
@RestController
@Slf4j
public class LineLoginApplication {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public static void main(final String... args) throws Exception {
        SpringApplication.run(LineLoginApplication.class, args);
    }

    @Value
    public static class LineUser {
        String displayName;
        String userId;
        URI pictureUrl;
        String statusMessage;
    }

    @Bean
    public PrincipalExtractor principalExtractor() {
        return map -> OBJECT_MAPPER.convertValue(map, LineUser.class);
    }

    @GetMapping("/")
    public Object whoami(
            @AuthenticationPrincipal final LineUser lineUser) {
        return lineUser;
    }
}