Skip to content

Commit

Permalink
Add backend spring secuirty
Browse files Browse the repository at this point in the history
  • Loading branch information
jonashonecker committed Jun 19, 2024
1 parent 305d01d commit fb6ff9c
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.github.jonashonecker.backend.security;

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

@GetMapping("/me")
public String getMe(@AuthenticationPrincipal OAuth2User user) {
return user.getAttributes().get("login").toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.github.jonashonecker.backend.security;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Value("${app.url}")
private String appUrl;

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(a -> a
.requestMatchers("/api/auth/me").authenticated()
.anyRequest().permitAll()
)
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.ALWAYS))
.exceptionHandling(e -> e
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
.oauth2Login(o -> o.defaultSuccessUrl(appUrl));
return http.build();
}
}
5 changes: 5 additions & 0 deletions backend/src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
spring.application.name=backend
spring.data.mongodb.uri=${MONGODB_URI}
spring.data.mongodb.database=TicketScout

spring.security.oauth2.client.registration.github.client-id=${OATUH_GITHUB_ID}
spring.security.oauth2.client.registration.github.client-secret=${OATUH_GITHUB_SECRET}
spring.security.oauth2.client.registration.github.scope=none
app.url=${APP_URL}

0 comments on commit fb6ff9c

Please sign in to comment.