asp.net MVC custom Validation Authorize Attribute

Source: Internet
Author: User
Tags cdata httpcontext json

This time insus.net in asp.net mvc to implement custom validation authorize Attribute.
Before implementation, insus.net to Usp_users_veryloginverify modified, to better understand and use:

SET ANSI_NULLS on
Go
SET QUOTED_IDENTIFIER ON
Go
ALTER PROCEDURE [dbo]. [Usp_users_veryloginverify]
(
@U_nbr NVARCHAR (20),
@pwd NVARCHAR (100)
)
As
BEGIN
DECLARE @errmsg NVARCHAR = N ' username or password error. '

IF not EXISTS (SELECT top 1 1 from [dbo].[ Users] WHERE [U_NBR] = @U_nbr)
BEGIN
RAISERROR (@errmsg, 16, 1)
Return
End

SELECT [U_NBR] as [account] from [dbo]. [Users] WHERE [U_NBR] = @U_nbr and CONVERT (NVARCHAR), Decryptbypassphrase (' insus#sec!%y ', [Pwd]) = @pwd

IF @ @ROWCOUNT <= 0
BEGIN
RAISERROR (@errmsg, 16, 1)
Return
End
End

Source Code
OK, above is the database aspect.

Then you need to write the program in asp.net MVC:

Use cookies to store login and authentication information, write a cookie category:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;

Namespace Insus.NET.Utilities
{
Public abstract class Cookiebase
{
private static HttpResponse Response
{
Get
{
return HttpContext.Current.Response;
}
}

private static HttpRequest Request
{
Get
{
return HttpContext.Current.Request;
}
}

public static HttpCookie Cookies
{
Get
{
return request.cookies["Cookiebase"] as HttpCookie;
}
Set
{
if (request.cookies["cookiebase"]!= null)
{
Request.Cookies.Remove ("Cookiebase");
}
RESPONSE.COOKIES.ADD (value);
}
}

        public static HttpCookie Newcookie
         {
            get
             {
                 return new HttpCookie ("Cookiebase");
           }
       }

public static void Removecookie ()
{
if (Cookie = null)
Response.Cookies.Remove ("Cookiebase");
Else
response.cookies["Cookiebase"]. Expires = DateTime.Now.AddDays (-1);
}
}
}

Source Code
In fact, this CookeBase.cs is a collection class that can store multiple objects. In a real program, what information do you want to store, you can write a class such as the following to operate:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using System.Web;

Namespace Insus.NET.Utilities
{
public class Securitybase
{
public static bool IsAuthorized
{
Get
{
return Cookiebase.cookie = null? False:bool. Parse (cookiebase.cookie.values["isauthorized"]);
}
Set
{
HttpCookie HttpCookie = Cookiebase.cookie = null? CookieBase.NewCookie:CookieBase.Cookie;
httpcookie.values["isauthorized"] = value. ToString ();
Cookiebase.cookie = HttpCookie;
}
}

public static string UserName
{
Get
{
return Cookiebase.cookie = null? String. empty:cookiebase.cookie.values["UserName"];
}
Set
{
HttpCookie HttpCookie = Cookiebase.cookie = null? CookieBase.NewCookie:CookieBase.Cookie;
httpcookie.values["UserName"] = value;
Cookiebase.cookie = HttpCookie;
}
}

public static void Removecooke ()
{
Cookiebase.removecookie ();
}
}
}

Source Code
Next, we need to create a validation filter:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using System.Web;
Using SYSTEM.WEB.MVC;
Using Insus.NET.Utilities;
Using System.Web.Routing;

Namespace Insus.NET.Attributes
{
    public class Securityauthorizeattribute: Authorizeattribute
    {
        protected override bool Authorizecore (httpcontextbase HttpContext)
        {
             return securitybase.isauthorized;
       }

        public override void Onauthorization (AuthorizationContext Filtercontext)
        {
             string controllername = FilterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            String actionname = filtercontext.actiondescriptor.actionname;          
            base. Onauthorization (Filtercontext);
       }

protected override void Handleunauthorizedrequest (AuthorizationContext filtercontext)
{
var RouteValue = new RouteValueDictionary {
{"Controller", "Home"},
{"Action", "Index"}
};
Filtercontext.result = new Redirecttorouteresult (RouteValue);
}
}
}

Source Code
This filter is SecurityAuthorizeAttribute.cs, and we'll apply it to the controller later.

Then you need to write the controller, no, we seem to write fewer objects, such as model and entity:


Models write well, but also a entity, this entity is connected with the data object:


In asp.net mvc, a demo of login validation requires a minimum of two controllers, one for anonymous users, and contains regular pages and basic operations. Another controller is a page that has been validated before it can be accessed.


Another controller:


Finally, the view is created:

@{
Layout = null;
}

<! DOCTYPE html>

<meta name= "viewport" content= "Width=device-width"/>
<title>Index</title>

<style type= "Text/css" >
#logincontact Label {
Display:inline-block;
width:100px;
Text-align:right;
}

#logincontact_submit {
padding-left:100px;
}

#logincontact Div {
Margin-top:1em;
}

. Error {
Display:none;
margin-left:10px;
}

. error_show {
color:red;
margin-left:10px;
}

Input.invalid {
BORDER:2PX solid red;
}

Input.valid {
BORDER:2PX solid Green;
}
</style>

<script src= "~/scripts/jquery-2.2.1.js" ></script>

<script type= "Text/javascript" >
<! [cdata[
$ (document). Ready (function () {
$ (' #logincontact_Account '). On (' Input ', function () {
var input = $ (this);
var is_account = Input.val ();
if (Is_account) {
Input.removeclass ("Invalid"). AddClass ("valid");
}
else {
Input.removeclass ("valid"). AddClass ("invalid");
}
});


$ (' #logincontact_Password '). On (' Input ', function () {
var input = $ (this);
var Is_password = Input.val ();
if (Is_password) {
Input.removeclass ("Invalid"). AddClass ("valid");
}
else {
Input.removeclass ("valid"). AddClass ("invalid");
}
});


$ (' #ButtonSignIn '). Click (Function (event) {
var form_data = $ ("#logincontact"). Serializearray ();
var error_free = true;
for (var input in form_data) {
var element = $ ("#logincontact_" + form_data[input][' name ');
var valid = Element.hasclass ("valid");
var error_element = $ ("span", element.parent ());

if (!valid) {
Error_element.removeclass ("Error"). AddClass ("Error_show");
Error_free = false;
}
else {
Error_element.removeclass ("Error_show"). AddClass ("error");
}
}

                if (!error_free) {
                     Event.preventdefault ();
               }
                else {
                     var obj = {};
                     obj. Account = $ (' #logincontact_Account '). Val (),
                     obj. Password = $ (' #logincontact_Password '). Val ()

$.ajax ({
Type: ' POST ',
URL: '/home/loginverify ',
DataType: ' JSON ',
Data:JSON.stringify (obj),
ContentType: ' Application/json; Charset=utf-8 ',
Success:function (data, textstatus) {
Alert ("Login succeeded.") ");
Window.location.href = "/user/index";
},
Error:function (XMLHttpRequest, Textstatus, Errorthrown) {
alert (Errorthrown);
},
});
}
});
});
]]>
</script>
<body>
<form id= "Logincontact" method= "POST" action= "" >
<div>
<label for= "Logincontact_account" >Account:</label>
<input type= "text" id= "Logincontact_account" name= "account"/>
<span class= "Error" >this account field is required.</span>
</div>
<div>
<label for= "Logincontact_password" >Password:</label>
<input type= "Password" id= "Logincontact_password" name= "password"/>
<span class= "error" >this password field is required.</span>
</div>
<div id= "Logincontact_submit" >
<input id= "Buttonsignin" type= "button" value= "Sign in"/>
</div>
</form>
</body>

Source Code
There is one more:

@{
Layout = null;
}

<! DOCTYPE html>
<meta name= "viewport" content= "Width=device-width"/>
<title>Index</title>
<script src= "~/scripts/jquery-2.2.1.js" ></script>

<script type= "Text/javascript" >
<! [cdata[
$ (document). Ready (function () {

$ (' #ButtonSignOut '). Click (Function (event) {
$.ajax ({
Type: ' POST ',
URL: '/home/signout ',
ContentType: ' Application/json; Charset=utf-8 ',
Success:function (data, textstatus) {
Alert ("The site has been safely exited.) ");
Window.location.href = "/home/index";
},
Error:function (XMLHttpRequest, Textstatus, Errorthrown) {
alert (Errorthrown);
},
});
});
});
]]>
</script>
<body>
<div>
Hi @ViewBag. UserName
<br/>
<input id= "buttonsignout" type= "button" value= "Sign out"/>
</div>
</body>

Source Code

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.