play framework学习笔记之 身份识别,openID

本文介绍了一个使用Play框架实现OpenID身份验证的简单示例。该示例覆盖了从用户请求检查到OpenID验证及保存验证后的OpenID到HTTP会话的全过程。通过提供的代码示例和模板,读者可以了解到如何集成OpenID认证功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

A simple OpenID authentication example

 

This example provides a high-level view of how OpenID authentication can be used within a Play application:

  • For each request, check if the user is connected
  • If not, display a page where the user can submit his OpenID
  • Redirect the user to the OpenID provider
  • When the user comes back, get the verified OpenID and save it in the HTTP session.

The OpenID functionality is provided by the play.libs.OpenID class.

@Before(unless={"login", "authenticate"})
static void checkAuthenticated() {
    if(!session.contains("user")) {
        login();
    }
}
 
public static void index() {
    render("Hello %s!", session.get("user"));
}
     
public static void login() {
    render();
}
    
public static void authenticate(String user) {
    if(OpenID.isAuthenticationResponse()) {
        UserInfo verifiedUser = OpenID.getVerifiedID();
        if(verifiedUser == null) {
            flash.error("Oops. Authentication has failed");
            login();
        } 
        session.put("user", verifiedUser.id);
        index();
    } else {
        if(!OpenID.id(user).verify()) { // will redirect the user
            flash.error("Cannot verify your OpenID");
            login();
        } 
    }
}

And the login.html template:

#{if flash.error}
<h1>${flash.error}</h1>
#{/if}
 
<form action="@{Application.authenticate()}" method="POST">
    <label for="user">What’s your OpenID?</label>
    <input type="text" name="user" id="user" />
    <input type="submit" value="login..." />
</form>
</code>

And finally the routes definitions:

GET   /                     Application.index
GET   /login                Application.login
*     /authenticate         Application.authenticate

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值