CAS implementation in spring MVC

Source: Internet
Author: User

CAS implementation in spring MVC
Concept:

 

SSO: Single Sign On Single Sign-On. SSO is one of multiple application systems. Users only need to log on once to access all mutually trusted application systems.

 

Principle:

 

 

This is the system schematic of CAS. It is only the first time the system is verified. The subsequent verification will be much clearer.

 

Implementation:

 

If we want to know how CAS is implemented in MVC, we need to understand the MVC Framework. Among them, MVC has two objects. I think it is very important to know:

 

1. Membership object: verifies user creden。 and manages user settings.

2. FormsAuthentication object: Manage the Forms authentication service for Web applications.

 

This makes it clear that the Membership object is the information we need to verify in the CAS Server. It contains the user's database. The FormsAuthentication object helps us generate cookies and ST. The architecture in spring MVC is well encapsulated and we cannot see how it is implemented, but we can know how to use them.

 

Create an MVC Controller:

 

 

Namespace MvcApplication1.Controllers {public class AccountController: Controller {// GET:/Account/LogOn public ActionResult LogOn () {return View ();} // POST: /Account/LogOn [HttpPost] public ActionResult LogOn (LogOnModel model, string returnUrl) {if (ModelState. isValid) {if (Membership. validateUser (model. userName, model. password) {// The first parameter is the user's information, and the second parameter is whether the Cookie will persist FormsAuthenticati. On. setAuthCookie (model. userName, model. rememberMe); // store Cookie Information in the local HttpCookie cookie = FormsAuthentication. getAuthCookie (model. userName, model. rememberMe); cookie. name = selfUserInfo; cookie. expires = DateTime. now. addDays (1); Response. cookies. add (cookie); // MVC encapsulation to help us verify url Information. If (Url. IsLocalUrl (returnUrl) & returnUrl. Length> 1 & returnUrl. StartsWith (/)&&! ReturnUrl. StartsWith (//)&&! ReturnUrl. startsWith (/\) {return Redirect (returnUrl);} else {return RedirectToAction (Index, Home) ;}} else {ModelState. addModelError (, the user name or password provided is incorrect .);} // If an error occurs at this step, the return View (model);} // FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket (// 1, // version number. // Model. UserName, // UserName associated with the authentication ticket. // DateTime. Now, // Cookie sending time. // DateTime. Now. AddMinutes (20), // Cookie expiration date. // False, // true if the Cookie is persistent; otherwise, false. // Roles); // user-defined data stored in cookies. Roles is a role string Array // string encryptedTicket = FormsAuthentication. encrypt (authTicket); // encrypted // save to cookie // HttpCookie authCookie = // new HttpCookie (FormsAuthentication. formsCookieName, // encryptedTicket); // Response. cookies. add (authCookie); // GET:/Account/LogOff public ActionResult LogOff () {FormsAuthentication. signOut (); // string subkeyName; // subkeyName = selfUserInfo; // HttpCookie aCookie = Re Quest. cookies [selfUserInfo]; // aCookie. values. remove (subkeyName); // aCookie. expires = DateTime. now. addDays (1); // Response. cookies. add (aCookie); // var memberValidation = HttpContext. request. cookies. get (selfUserInfo); // The Cookie is queried from the local database, and then the Cookie is destroyed if (Request. cookies [selfUserInfo]! = Null) {HttpCookie mycookie; mycookie = Request. cookies [selfUserInfo]; Response. cookies [selfUserInfo]. expires = System. dateTime. now. addMonths (-1); Response. cookies. remove (selfUserInfo); // clear Response. cookies. add (mycookie); // write expired */Response. cookies [selfUserInfo]. expires = DateTime. now. addDays (-1);} var memberValidation = HttpContext. request. cookies. get (selfUserInfo); return RedirectToAction (Ind Ex, Home) ;}/// GET:/Account/Register public ActionResult Register () {return View () ;}/// POST: /Account/Register [HttpPost] public ActionResult Register (RegisterModel model) {if (ModelState. isValid) {// try to register the user MembershipCreateStatus createStatus; Membership. createUser (model. userName, model. password, model. email, null, null, true, null, out createStatus); if (createStatus = MembershipCr EateStatus. success) {// register a new member FormsAuthentication. setAuthCookie (login, false/* createPersistentCookie */); return RedirectToAction (Index, Home);} else {ModelState. addModelError (, ErrorCodeToString (createStatus); }}// if an error occurs at this step, the return View (model) form is re-displayed );} /// GET:/Account/ChangePassword [MemberValidation] public ActionResult ChangePassword () {return View () ;}/// POST:/Accou Nt/ChangePassword [MemberValidation] [HttpPost] public ActionResult ChangePassword (ChangePasswordModel model) {if (ModelState. isValid) {// in some cases, ChangePassword will throw an exception, // instead of returning false. Bool changePasswordSucceeded; try {MembershipUser currentUser = Membership. getUser (User. identity. name, true/* userIsOnline */); changePasswordSucceeded = currentUser. changePassword (model. oldPassword, model. newPassword);} catch (Exception) {changePasswordSucceeded = false;} if (changePasswordSucceeded) {return RedirectToAction (ChangePasswordSuccess);} else {ModelState. addModelError (, the current password is incorrect True or the new password is invalid .);} // If an error occurs at this step, the return View (model) form is re-displayed;} // GET: /Account/ChangePasswordSuccess public ActionResult ChangePasswordSuccess () {return View ();} # region Status Codes private static string ErrorCodeToString (MembershipCreateStatus createStatus) {// see http://go.microsoft.com/fwlink? LinkID = 177550 to view the complete list of // status code. Switch (createStatus) {case MembershipCreateStatus. DuplicateUserName: return the user name already exists. Enter a different user name .; Case MembershipCreateStatus. DuplicateEmail: return the User Name of the email address already exists. Enter different email addresses .; Case MembershipCreateStatus. InvalidPassword: the password provided by return is invalid. Enter a valid password .; Case MembershipCreateStatus. InvalidEmail: the email address provided by return is invalid. Check the value and try again .; Case MembershipCreateStatus. InvalidAnswer: The returned password is invalid. Check the value and try again .; Case MembershipCreateStatus. InvalidQuestion: the password retrieval problem provided by return is invalid. Check the value and try again .; Case MembershipCreateStatus. InvalidUserName: the user name provided by return is invalid. Check the value and try again .; Case MembershipCreateStatus. ProviderError: The return Authentication provider returned an error. Verify your input and try again. If the problem persists, contact the system administrator .; Case MembershipCreateStatus. UserRejected: return the User Creation request has been canceled. Verify your input and try again. If the problem persists, contact the system administrator .; Default: return: an unknown error occurs. Verify your input and try again. If the problem persists, contact the system administrator .; }}# Endregion public ActionResult ValidateCode () {ValidateCodeHelper helper = new ValidateCodeHelper (); string strCode = helper. createValidateCode (4); Session [validateCode] = strCode; var byteData = helper. createValidateGraphic (strCode); return File (byteData, image/jpeg );}}}

We can see that there is such a tag [MemberValidation] on the Action to be added.

 

 

Then we need to write such a feature AuthorizeAttribute:

 

Let's create a class to integrate this feature:

 

 

Public class MemberValidationAttribute: AuthorizeAttribute {public override void OnAuthorization (AuthorizationContext filterContext) {// obtain Login // var memberValidation = System in Cookies. web. httpContext. current. request. cookies. get (login); // var memberValidation = filterContext. httpContext. user. identity. name; var memberValidation = filterContext. httpContext. request. cookies. get (selfUserInfo); // if memberValidation is null or memberValidation is not equal to Success if (memberValidation = null) {// The page jumps to the login page filterContext. result = new RedirectToRouteResult (new RouteValueDictionary (new {controller = Account, action = LogOn}); return ;}// return verified ;}}

The general meaning is actually very simple. I will check whether there is a Cookie on the local device. If there is a Cookie, We will verify it. If not, we will verify it from the New login interface.

 

 

Create an access page HomePage:

 

 

    public class HomePageController : Controller    {        //        // GET: /HomePage/        [MemberValidation]        public ActionResult HomePage()        {            return View();        }    }

On this page, we load all the application systems and turn this page into a portal.

 

 

Take a look at HomePage. cshtml:

 

 

@{    ViewBag.Title = Index;}
@ * <Script src = .. /.. /Scripts/addPage. js> </script> * @ * <script src = .. /.. /Scripts/EasyuiLayout. js> </script> *@ <Script type = text/javascript src = .. /.. /Content/jquery-easyui-1.3.2/jquery-1.8.0.min.js> </script> <script type = text/javascript src = .. /.. /Content/jquery-easyui-1.3.2/jquery. easyui. min. js> </script> <script type = text/javascript src = .. /.. /Content/jquery. balloon. js> </script> <script src = .. /.. /Content/jquery-easyui-1.3.2/locale/easyui-lang-zh_CN.js> </script> <Script src =..././Scripts/MyScript/ITOO_Common.js> </script> <Script> function addTab (tableName, controlerAddress) {$ (# tt ). tabs ('add', {title: tableName, content: ''+ '<iframe id = abc name = PageFrame frameBorder = 0 width = 100% height = 100% src =' + controlerAddress + '>' + '</iframe>' +'', closable: true}) ;}</script>
As you can see, we can access the newly generated report interface by using the ip port number and controller/Action, in the action of FreshStudentReportController's FreshStudentReport, We need to label [MemberValidation] to continue to judge whether a Cookie exists locally and allow it to verify.

 

 

Summary:

 

The spring MVC framework itself is well encapsulated. To learn how to use it, we need to understand the objects involved in it. In fact, we have always wanted to implement verification in various systems. We didn't understand the problem, that is, the Cookie is stored in a local browser and is only stored locally, we can make various judgments and verifications. Otherwise, there is no way to see whether the user has permissions, or after a user logs in, all users can access all systems without authentication.

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.