ASP.NET MVC实现单点登录,SSO小Demo

地址:http://www.oschina.net/code/snippet_1993919_49158

1. [代码]AccountController(SSOLogin)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Web;

usingSystem.Web.Mvc;

usingSystem.Web.Security;

namespaceSSOLogin.Controllers

{

publicclassAccountController : Controller

{

[AllowAnonymous]

publicActionResult Login(stringreturnUrl)

{

if(Request.IsAuthenticated)

{

returnRedirectToAction("Index","Home");

}

ViewBag.returnUrl = returnUrl;

returnView();

}

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

publicActionResult Login(stringusername,stringpassword,stringreturnUrl)

{

if(FormsAuthentication.Authenticate(username, password))

{

FormsAuthentication.SetAuthCookie(username,false);

if(!string.IsNullOrEmpty(returnUrl))

{

returnRedirect(returnUrl);

}

else

{

returnRedirectToAction("Index","Home");

}

}

else

{

ModelState.AddModelError(string.Empty,"Invalid Detail!");

ViewBag.returnUrl = returnUrl;

returnView();

}

}

}

}

2. [代码]Login.cshtml(SSOLoin)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

@{

ViewBag.Title ="Login";

}

<h2>Login</h2>

@using(Html.BeginForm(new{ returnUrl = ViewBag.returnUrl }))

{

@Html.ValidationSummary()

@Html.AntiForgeryToken()

<divclass="form-group">

@Html.Label("Username")

@Html.Editor("Username")

</div>

<divclass="form-group">

@Html.LabelForModel("Password")

@Html.Password("Password")

</div>

<inputclass="btn btn-primary"type="submit"value="login"/>

}

3. [代码]web.config(ssoLogin)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

<?xml version="1.0"encoding="utf-8"?>

<!--

For more informationonhow to configure your ASP.NET application, please visit

http://go.microsoft.com/fwlink/?LinkId=169433

-->

<configuration>

<configSections>

<!-- For more informationonEntity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->

<section name="entityFramework"type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"requirePermission="false"/>

</configSections>

<connectionStrings>

<add name="DefaultConnection"connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-SSOLogin-20150701143055;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-SSOLogin-20150701143055.mdf"providerName="System.Data.SqlClient"/>

</connectionStrings>

<appSettings>

<add key="webpages:Version"value="2.0.0.0"/>

<add key="webpages:Enabled"value="false"/>

<add key="PreserveLoginUrl"value="true"/>

<add key="ClientValidationEnabled"value="true"/>

<add key="UnobtrusiveJavaScriptEnabled"value="true"/>

</appSettings>

<system.web>

<compilation debug="true"targetFramework="4.5"/>

<httpRuntime targetFramework="4.5"/>

<authentication mode="Forms">

<forms loginUrl="http://16.187.25.23:9001/Account/Login"timeout="2880">

<credentials passwordFormat="SHA1">

<user name="demo"password="89e495e7941cf9e40e6980d14a16bf023ccd4c91"/>

<!--password = demo-->

</credentials>

</forms>

</authentication>

<pages>

<namespaces>

<addnamespace="System.Web.Helpers"/>

<addnamespace="System.Web.Mvc"/>

<addnamespace="System.Web.Mvc.Ajax"/>

<addnamespace="System.Web.Mvc.Html"/>

<addnamespace="System.Web.Optimization"/>

<addnamespace="System.Web.Routing"/>

<addnamespace="System.Web.WebPages"/>

</namespaces>

</pages>

<machineKey decryption="AES"decryptionKey="B1604C0351F94A670B483E6C0823B972F317AD1CD4527969"validation="SHA1"validationKey="F332ABBCC2D28648F0842871A0309E3D59CB5DCDA9141D489D5417DC72F386EE4872F5CD7CB443D1C4CDC6E9B1C8F53EF4D9272137692F632DFB5E8F13A9BE85"/>

</system.web>

<system.webServer>

<validation validateIntegratedModeConfiguration="false"/>

<handlers>

<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit"/>

<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"/>

<remove name="ExtensionlessUrlHandler-Integrated-4.0"/>

<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit"path="*."verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"modules="IsapiModule"scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll"preCondition="classicMode,runtimeVersionv4.0,bitness32"responseBufferLimit="0"/>

<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"path="*."verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"modules="IsapiModule"scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"preCondition="classicMode,runtimeVersionv4.0,bitness64"responseBufferLimit="0"/>

<add name="ExtensionlessUrlHandler-Integrated-4.0"path="*."verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"type="System.Web.Handlers.TransferRequestHandler"preCondition="integratedMode,runtimeVersionv4.0"/>

</handlers>

</system.webServer>

<runtime>

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

<dependentAssembly>

<assemblyIdentity name="System.Web.Helpers"publicKeyToken="31bf3856ad364e35"/>

<bindingRedirect oldVersion="1.0.0.0-2.0.0.0"newVersion="2.0.0.0"/>

</dependentAssembly>

<dependentAssembly>

<assemblyIdentity name="System.Web.Mvc"publicKeyToken="31bf3856ad364e35"/>

<bindingRedirect oldVersion="1.0.0.0-4.0.0.0"newVersion="4.0.0.0"/>

</dependentAssembly>

<dependentAssembly>

<assemblyIdentity name="System.Web.WebPages"publicKeyToken="31bf3856ad364e35"/>

<bindingRedirect oldVersion="1.0.0.0-2.0.0.0"newVersion="2.0.0.0"/>

</dependentAssembly>

</assemblyBinding>

</runtime>

<entityFramework>

<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>

</entityFramework>

</configuration>

4. [代码]HomeController(webapp1和webapp2)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Web;

usingSystem.Web.Mvc;

namespaceWebApp2.Controllers

{

[Authorize]

publicclassHomeController : Controller

{

//

// GET: /Home/

publicActionResult Index()

{

returnView();

}

}

}

5. [代码]web.config(webapp1和webapp2)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

<?xml version="1.0"encoding="utf-8"?>

<!--

For more informationonhow to configure your ASP.NET application, please visit

http://go.microsoft.com/fwlink/?LinkId=152368

-->

<configuration>

<configSections>

<!-- For more informationonEntity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->

<section name="entityFramework"type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"requirePermission="false"/>

</configSections>

<connectionStrings>

<add name="DefaultConnection"providerName="System.Data.SqlClient"connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WebApp1-20150701143240;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-WebApp1-20150701143240.mdf"/>

</connectionStrings>

<appSettings>

<add key="webpages:Version"value="2.0.0.0"/>

<add key="webpages:Enabled"value="false"/>

<add key="PreserveLoginUrl"value="true"/>

<add key="ClientValidationEnabled"value="true"/>

<add key="UnobtrusiveJavaScriptEnabled"value="true"/>

</appSettings>

<system.web>

<httpRuntime targetFramework="4.5"/>

<compilation debug="true"targetFramework="4.5"/>

<authentication mode="Forms">

<forms loginUrl="http://16.187.25.23:9001/Account/Login"timeout="2880">

</forms>

</authentication>

<pages>

<namespaces>

<addnamespace="System.Web.Helpers"/>

<addnamespace="System.Web.Mvc"/>

<addnamespace="System.Web.Mvc.Ajax"/>

<addnamespace="System.Web.Mvc.Html"/>

<addnamespace="System.Web.Optimization"/>

<addnamespace="System.Web.Routing"/>

<addnamespace="System.Web.WebPages"/>

</namespaces>

</pages>

<profile defaultProvider="DefaultProfileProvider">

<providers>

<add name="DefaultProfileProvider"type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"connectionStringName="DefaultConnection"applicationName="/"/>

</providers>

</profile>

<membership defaultProvider="DefaultMembershipProvider">

<providers>

<add name="DefaultMembershipProvider"type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"connectionStringName="DefaultConnection"enablePasswordRetrieval="false"enablePasswordReset="true"requiresQuestionAndAnswer="false"requiresUniqueEmail="false"maxInvalidPasswordAttempts="5"minRequiredPasswordLength="6"minRequiredNonalphanumericCharacters="0"passwordAttemptWindow="10"applicationName="/"/>

</providers>

</membership>

<roleManager defaultProvider="DefaultRoleProvider">

<providers>

<add name="DefaultRoleProvider"type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"connectionStringName="DefaultConnection"applicationName="/"/>

</providers>

</roleManager>

<sessionState mode="InProc"customProvider="DefaultSessionProvider">

<providers>

<add name="DefaultSessionProvider"type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"connectionStringName="DefaultConnection"/>

</providers>

</sessionState>

<machineKey decryptionKey="553663C339D113C9B9EF1DEFFD9E6DD5B1B9BEBD01AAA51A"validation="SHA1"validationKey="08A0B67867C2BD7235BABF1B9506A5F8F7A1E2565539C151F9F42DCC324A07263E8AB9C5865F08B1B242B2B6C79D32A77A23D57CF0B4E7CCCFAD230EDED1A9DA"/>

</system.web>

<system.webServer>

<validation validateIntegratedModeConfiguration="false"/>

<handlers>

<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit"/>

<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"/>

<remove name="ExtensionlessUrlHandler-Integrated-4.0"/>

<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit"path="*."verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"modules="IsapiModule"scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll"preCondition="classicMode,runtimeVersionv4.0,bitness32"responseBufferLimit="0"/>

<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"path="*."verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"modules="IsapiModule"scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"preCondition="classicMode,runtimeVersionv4.0,bitness64"responseBufferLimit="0"/>

<add name="ExtensionlessUrlHandler-Integrated-4.0"path="*."verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"type="System.Web.Handlers.TransferRequestHandler"preCondition="integratedMode,runtimeVersionv4.0"/>

</handlers>

</system.webServer>

<runtime>

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

<dependentAssembly>

<assemblyIdentity name="System.Web.Helpers"publicKeyToken="31bf3856ad364e35"/>

<bindingRedirect oldVersion="1.0.0.0-2.0.0.0"newVersion="2.0.0.0"/>

</dependentAssembly>

<dependentAssembly>

<assemblyIdentity name="System.Web.Mvc"publicKeyToken="31bf3856ad364e35"/>

<bindingRedirect oldVersion="1.0.0.0-4.0.0.0"newVersion="4.0.0.0"/>

</dependentAssembly>

<dependentAssembly>

<assemblyIdentity name="System.Web.WebPages"publicKeyToken="31bf3856ad364e35"/>

<bindingRedirect oldVersion="1.0.0.0-2.0.0.0"newVersion="2.0.0.0"/>

</dependentAssembly>

</assemblyBinding>

</runtime>

<entityFramework>

<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>

</entityFramework>

</configuration>