0

我一直在尝试自学更多关于后端开发的知识,因此我选择了 spring/java/kotlin 作为我的工具。从教程中,我尝试通过 github 设置 oauth2,但它似乎无法正常工作。

我的要求:

  1. 创建一个网站,在誓言登录后包含一些页面:比如说/about/index.html是无需登录即可访问的页面

  2. 特定页面上的 cta x(比如“登录查看”按钮/market)将打开 github 登录页面,成功登录后,我们将用户重定向到页面y(比如/marketmarket-unlocked

  3. 我可以将某种令牌或其他标识符存储在我的数据库中,这样下次打开该页面时,我不会向他们显示 github 登录名,而是直接打开它。这也必须为 rest apis 完成,例如/user/{id}端点返回 userinfo ,因此应该在使用 github 登录后访问(我们将发送身份验证令牌作为标头,对吗?)


这是我尝试过的代码:

我的 applications.properties 文件:

spring.security.oauth2.client.registration.github.client-id=REDACTED
spring.security.oauth2.client.registration.github.client-secret=REDACTED
spring.security.oauth2.client.registration.github.redirect-uri=http://localhost:8080/userinfo
spring.security.oauth2.client.registration.github.scope=email,public_profile

我的 application.kt 文件

@SpringBootApplication
class PMartApplication: ApplicationListener<ApplicationEvent> {
    override fun onApplicationEvent(event: ApplicationEvent) { event.log() }

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            runApplication<PMartApplication>(*args)
        }
    }
}

我的 securityconfigadapter.kt 文件:

@Configuration
@EnableWebSecurity
class PMartSecurityAdapterConfig: WebSecurityConfigurerAdapter() , PMartConfig {
    override fun configure(http: HttpSecurity?) {
       
        http?.authorizeRequests()                      
            ?.antMatchers("/","/error**","/userinfo")?.permitAll()
            ?.anyRequest()?.authenticated()?.and()?.oauth2Login()
    }
}

我的登录 apis 控制器文件:

@RestController
class AuthApis : PMartApiControllers {

    @Autowired
    var oacis: OAuth2AuthorizedClientService? = null


    @GetMapping("/login")
    fun login(): Map<String, String> {
        return mapOf("response" to "logged in success")
    }


    @GetMapping("/logout")
    fun logout(): Map<String, String> {
        return mapOf("response" to "log out success")
    }

    @GetMapping("/user")
    fun user(@AuthenticationPrincipal user: OAuth2User?): Map<String,String> {
        return mapOf("user" to user.toJsonString(true))
    }

    @GetMapping("/clientinfo")
    fun clientinfo(model: Model?, token: OAuth2AuthenticationToken?): Map<String, String> {
        return token.getInfoMap(oacis)
    }

    @GetMapping("/userinfo")
    fun userinfo(model: Model?, token: OAuth2AuthenticationToken?): Map<String, String> {
       return token.getInfoMap(oacis)
    }

    @GetMapping("/redi")
    fun getRedirect(resp: HttpServletResponse?, request: HttpServletRequest?):Authentication  {
        val auth: Authentication = SecurityContextHolder.getContext().authentication
        auth.log()
        return  auth
    }

}

我的 github 配置: 在此处输入图像描述

现在的情况:

  1. 我能够使“/”、“/error”、“/payments”等端点无需登录即可访问,其他路径可通过登录访问
  2. 对于登录,在打开中提到的端点后,它并没有真正给出任何令牌AuthApi.kt
  3. github api 还限制 github 应用程序和属性中的重定向 url 都相同。我不想要这样的限制,并想确定每个登录请求的重定向 url
  4. 整个登录无法正常工作

有人可以帮助我了解如何解决这些问题吗?非常感谢。

4

0 回答 0