You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

sso.go 4.4 kB

Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package sso
  6. import (
  7. "fmt"
  8. "reflect"
  9. "strings"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/setting"
  13. "gitea.com/macaron/macaron"
  14. "gitea.com/macaron/session"
  15. )
  16. // ssoMethods contains the list of SSO authentication plugins in the order they are expected to be
  17. // executed.
  18. //
  19. // The OAuth2 plugin is expected to be executed first, as it must ignore the user id stored
  20. // in the session (if there is a user id stored in session other plugins might return the user
  21. // object for that id).
  22. //
  23. // The Session plugin is expected to be executed second, in order to skip authentication
  24. // for users that have already signed in.
  25. var ssoMethods = []SingleSignOn{
  26. &OAuth2{},
  27. &Session{},
  28. &ReverseProxy{},
  29. &Basic{},
  30. }
  31. // The purpose of the following three function variables is to let the linter know that
  32. // those functions are not dead code and are actually being used
  33. var (
  34. _ = handleSignIn
  35. )
  36. // Methods returns the instances of all registered SSO methods
  37. func Methods() []SingleSignOn {
  38. return ssoMethods
  39. }
  40. // Register adds the specified instance to the list of available SSO methods
  41. func Register(method SingleSignOn) {
  42. ssoMethods = append(ssoMethods, method)
  43. }
  44. // Init should be called exactly once when the application starts to allow SSO plugins
  45. // to allocate necessary resources
  46. func Init() {
  47. for _, method := range Methods() {
  48. err := method.Init()
  49. if err != nil {
  50. log.Error("Could not initialize '%s' SSO method, error: %s", reflect.TypeOf(method).String(), err)
  51. }
  52. }
  53. }
  54. // Free should be called exactly once when the application is terminating to allow SSO plugins
  55. // to release necessary resources
  56. func Free() {
  57. for _, method := range Methods() {
  58. err := method.Free()
  59. if err != nil {
  60. log.Error("Could not free '%s' SSO method, error: %s", reflect.TypeOf(method).String(), err)
  61. }
  62. }
  63. }
  64. // SessionUser returns the user object corresponding to the "uid" session variable.
  65. func SessionUser(sess session.Store) *models.User {
  66. // Get user ID
  67. uid := sess.Get("uid")
  68. if uid == nil {
  69. return nil
  70. }
  71. id, ok := uid.(int64)
  72. if !ok {
  73. return nil
  74. }
  75. // Get user object
  76. user, err := models.GetUserByID(id)
  77. if err != nil {
  78. if !models.IsErrUserNotExist(err) {
  79. log.Error("GetUserById: %v", err)
  80. }
  81. return nil
  82. }
  83. return user
  84. }
  85. // isAPIPath returns true if the specified URL is an API path
  86. func isAPIPath(ctx *macaron.Context) bool {
  87. return strings.HasPrefix(ctx.Req.URL.Path, "/api/")
  88. }
  89. // isAttachmentDownload check if request is a file download (GET) with URL to an attachment
  90. func isAttachmentDownload(ctx *macaron.Context) bool {
  91. return strings.HasPrefix(ctx.Req.URL.Path, "/attachments/") && ctx.Req.Method == "GET"
  92. }
  93. // handleSignIn clears existing session variables and stores new ones for the specified user object
  94. func handleSignIn(ctx *macaron.Context, sess session.Store, user *models.User) {
  95. _ = sess.Delete("openid_verified_uri")
  96. _ = sess.Delete("openid_signin_remember")
  97. _ = sess.Delete("openid_determined_email")
  98. _ = sess.Delete("openid_determined_username")
  99. _ = sess.Delete("twofaUid")
  100. _ = sess.Delete("twofaRemember")
  101. _ = sess.Delete("u2fChallenge")
  102. _ = sess.Delete("linkAccount")
  103. err := sess.Set("uid", user.ID)
  104. if err != nil {
  105. log.Error(fmt.Sprintf("Error setting session: %v", err))
  106. }
  107. err = sess.Set("uname", user.Name)
  108. if err != nil {
  109. log.Error(fmt.Sprintf("Error setting session: %v", err))
  110. }
  111. // Language setting of the user overwrites the one previously set
  112. // If the user does not have a locale set, we save the current one.
  113. if len(user.Language) == 0 {
  114. user.Language = ctx.Locale.Language()
  115. if err := models.UpdateUserCols(user, "language"); err != nil {
  116. log.Error(fmt.Sprintf("Error updating user language [user: %d, locale: %s]", user.ID, user.Language))
  117. return
  118. }
  119. }
  120. ctx.SetCookie("lang", user.Language, nil, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  121. // Clear whatever CSRF has right now, force to generate a new one
  122. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  123. }