역할 정보가 포함된 FormsAuthentication 인증

6357 단어 Authentication
단계:
1. 로그인할 때 FormsAuthenticationTicket를 수동으로 설정합니다. 코드는 다음과 같습니다.

  
    
  // FormsAuthenticationTicket
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket( 1 , "username " , DateTime.Now, DateTime.Now.AddMinutes( 20 ), false , " admin " );
//
  string HashTicket = FormsAuthentication.Encrypt(Ticket);
// cookie
HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);  
// Cookie
Response.Cookies.Add(UserCookie);

2. Global에 다음 코드를 추가합니다.

  
    
     protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
// Construst the GeneralPrincipal and FormsIdentity objects
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];

if ( null == authCookie)
{
// no authentication cokie present
return ;
}

FormsAuthenticationTicket authTicket
= FormsAuthentication.Decrypt(authCookie.Value);

if ( null == authTicket)
{
// could not decrypt cookie
return ;
}

// get the role
string [] role = authTicket.UserData.Split( new char [] { ' , ' });
FormsIdentity id
= new FormsIdentity(authTicket);

Context.User
= new GenericPrincipal(id, role);
}

이렇게 하면 우리는 프로그램에서 [Authorize(Roles="admin")]를 사용하여 검증할 수 있다.

좋은 웹페이지 즐겨찾기